package com.mingqijia.gassafety.webserver.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gap.basic.exception.BizException;
import com.gap.cache.redis.RedisCache;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.util.StringUtil;
import com.mingqijia.gassafety.authority.api.resp.config.DictionaryItemRespDTO;
import com.mingqijia.gassafety.authority.dal.helper.ConfigureHolder;
import com.mingqijia.gassafety.db.entity.*;
import com.mingqijia.gassafety.db.entity.Dictionary;
import com.mingqijia.gassafety.db.entity.auth.CompanyEntry;
import com.mingqijia.gassafety.db.entity.redis.LatestLog;
import com.mingqijia.gassafety.db.entity.vo.*;
import com.mingqijia.gassafety.shared.dto.LogVO;
import com.mingqijia.gassafety.db.influxdb.config.InfluxDBConfiguration;
import com.mingqijia.gassafety.db.influxdb.config.InfluxDBConnect;
import com.mingqijia.gassafety.db.mapper.*;
import com.mingqijia.gassafety.db.mapper.auth.CompanyMapper;
import com.mingqijia.gassafety.shared.constant.*;
import com.mingqijia.gassafety.shared.handler.GlobalAuthenticationException;
import com.mingqijia.gassafety.shared.utils.ApplicationUtils;
import com.mingqijia.gassafety.shared.utils.CompareUtil;
import com.mingqijia.gassafety.shared.utils.FileUtil;
import com.mingqijia.gassafety.shared.utils.RedisCacheExt;
import com.mingqijia.gassafety.shared.utils.commonUtils.BeanConvertUtils;
import com.mingqijia.gassafety.shared.utils.commonUtils.DateUtils;
import com.mingqijia.gassafety.shared.utils.commonUtils.LocationUtil;
import com.mingqijia.gassafety.shared.utils.commonUtils.PageUtil;
import com.mingqijia.gassafety.shared.vcc.VccAuthoritiesProvider;
import com.mingqijia.gassafety.webserver.constant.DeviceConstant;
import com.mingqijia.gassafety.shared.dto.UserFuncCodePermissionDTO;
import com.mingqijia.gassafety.webserver.feign.ConsoleSkFeignClient;
import com.mingqijia.gassafety.webserver.feign.SmartKitchenFeignClient;
import com.mingqijia.gassafety.webserver.request.*;
import com.mingqijia.gassafety.webserver.request.console.sk.HomeDeviceBindNoticeRequest;
import com.mingqijia.gassafety.webserver.request.inner.AddressTurnCoordinateReq;
import com.mingqijia.gassafety.webserver.request.tcis.UnbindAlarmRequest;
import com.mingqijia.gassafety.webserver.response.*;
import com.mingqijia.gassafety.webserver.response.baidu.BaiDuDetailResp;
import com.mingqijia.gassafety.webserver.response.sk.AlarmSupplierListVo;
import com.mingqijia.gassafety.webserver.response.sk.ConsoleSkSupplierListResponse;
import com.mingqijia.gassafety.webserver.service.*;
import com.mingqijia.gassafety.webserver.service.cmp.EquipmentCmpService;
import com.mingqijia.gassafety.webserver.service.workorder.WorkOrderHistoryService;
import com.mingqijia.gassafety.webserver.service.workorder.mbp.MbpWorkOrderService;
import com.mingqijia.gassafety.webserver.service.workorder.mbp.TcisService;
import com.mingqijia.gassafety.webserver.utils.CoordinatesTransitionUtil;
import com.mingqijia.gassafety.webserver.utils.LogRecordAspect;
import com.mingqijia.gassafety.webserver.utils.LogUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.influxdb.dto.QueryResult;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static com.mingqijia.gassafety.shared.constant.Constants.*;
import static com.mingqijia.gassafety.webserver.constant.DeviceConstant.*;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author wanghai
 * @since 2022-02-22
 */
@Service
@Slf4j
public class ConsumerServiceImpl extends ServiceImpl<ConsumerMapper, Consumer> implements ConsumerService {
    @Value("${baidu.maps.key}")
    private String baiDuMapsKey;

    private static final String CUST_TYPE_ENUM = "cust_type_enum";

    @Value("${gassafety.hangzhou.yhSpId}")
    private String hangzhouSpId;
    @Value(value = "${gassafety.installationPosition.checkSwitch}")
    private boolean checkSwitch = true;
    @Autowired
    private CompareUtil compareUtil;
    @Autowired
    HangZhouService hangZhouService;
    @Autowired
    FieldTemplateMapper fieldTemplateMapper;
    @Autowired
    DeviceStateService deviceStateService;
    @Autowired
    DtuBindingOrderMapper dtuBindingOrderMapper;
    @Autowired
    DepartmentService departmentService;
    @Autowired
    RecordDetectorService recordDetectorService;
    @Autowired
    RecordControllerMapper recordControllerMapper;
    @Autowired
    DtuAepMapper dtuAepMapper;
    @Autowired
    ConsumerMapper consumerMapper;
    @Autowired
    ContactsService contactsService;
    @Autowired
    EquipmentService equipmentService;
    @Autowired
    RunningReportService runningReportService;
    @Autowired
    DtuMapper dtuMapper;
    @Autowired
    RedisCacheExt redisCacheExt;
    @Autowired
    DictionaryMapper dictionaryMapper;

    @Autowired
    DeviceStateMapper deviceStateMapper;

    @Autowired
    DivisionService divisionService;
    @Autowired
    LatestLogService latestLogService;
    @Autowired
    WarnStrategyService service;
    @Autowired
    InfluxDBConfiguration influxDBConfiguration;
    @Autowired
    ConfigureHolder holder;
    @Autowired
    WarnStrategyService warnStrategyService;
    @Autowired
    CompanyMapper companyMapper;
    @Autowired
    DepartmentMapper departmentMapper;
    @Autowired
    ConsumerDtuHistoryMapper consumerDtuHistoryMapper;
    @Autowired
    VccAuthoritiesProvider vccAuthoritiesProvider;
    @Autowired
    CompanyService companyService;
    @Autowired
    FileUploadMapper fileUploadMapper;
    @Autowired
    RedisCache redisCache;
    @Autowired
    CustomerSubsService customerSubsService;
    @Autowired
    ConsumerDtuHistoryService consumerDtuHistoryService;
    @Autowired
    MbpWorkOrderService mbpWorkOrderService;
    @Autowired
    OperationLogService operationLogService;
    @Autowired
    ReceiverValveService receiverValveService;
    @Autowired
    RecordReceiverValveService recordReceiverValveService;
    @Autowired
    SmartKitchenFeignClient smartKitchenFeignClient;
    @Autowired
    OrganizationService organizationService;
    @Autowired
    ValveInfoService valveInfoService;
    @Autowired
    DeviceSolenoidService deviceSolenoidService;
    @Autowired
    ConsumerServiceInfoService consumerServiceInfoService;
    @Autowired
    LogUtil logUtil;
    @Autowired
    FileUtil fileUtil;
    @Autowired
    CommonService commonService;
    @Autowired
    RecordControllerHistoryService controllerHistoryService;
    @Autowired
    RecordDetectorHistoryService detectorHistoryService;
    @Autowired
    RecordReceiverValveHistoryService receiverValveHistoryService;
    @Autowired
    WorkOrderHistoryService workOrderHistoryService;
    @Autowired
    CompanyCodeMapper companyCodeMapper;
    @Autowired
    ConsumerLocationService consumerLocationService;

    @Autowired
    ConsoleSkFeignClient consoleSkFeignClient;

    @Autowired
    FunctionAreaService functionAreaService;

    @Autowired
    UserPermissionService userPermissionService;

    @Autowired
    TcisService tcisService;

    @Autowired
    EquipmentCmpService equipmentCmpService;

    @Autowired
    LocationUtil locationUtil;

    @Autowired
    private BusinessNoticeService businessNoticeService;

    @Autowired
    private ServicePkgRecordMapper servicePkgRecordMapper;

    @Autowired
    private ContactsMapper contactsMapper;

    public static final String DIFFERENT_SERVICE_PACKAGE_MODE = "different_service_package_mode";

    private static final String phoneRegex = "^(1[3-9])\\d{9}$";
    private static final String landlineRegex = "\\d{3,4}[-]\\d{7,8}";
    private static final String landlineRegexs = "^\\d{3}$";
    private ExecutorService executor = Executors.newFixedThreadPool(10);
    private static int counter = 0; // 用于组成客户企业编码的流水号

    public Map<String,String> queryDictMapByCodeNoSpId(String dictCode, Map<String,String> defaultMap) {
        Map<String,String> map = new HashMap<>();
        QueryWrapper<Dictionary> dictionaryQueryWrapper = new QueryWrapper<>();
        dictionaryQueryWrapper.lambda()
                .eq(Dictionary::getIsDeleted, IS_DELETED_FALSE)
                .eq(Dictionary::getSpId, "0")
                .eq(Dictionary::getDictCode, dictCode);
        List<Dictionary> dictionaryList = dictionaryMapper.selectList(dictionaryQueryWrapper);
        if (CollectionUtil.isNotEmpty(dictionaryList)) {
            map = dictionaryList.stream().collect(Collectors.toMap(Dictionary::getValue, Dictionary::getAlias,(k1,k2)->k2));
        }
        else {
            map = defaultMap;
        }
        if (MapUtils.isEmpty(map)) map = defaultMap;
        return map;
    }

    @Override
    public PageUtil<ConsumerResponse> consumerList(ConsumerListRequest request) {
        String spId = ApplicationUtils.getWorkingSpId();
        Page<Consumer> page = null;
        QueryWrapper<Consumer> queryWrapper = new QueryWrapper<>();

        FieldTemplate fieldTemplate = fieldTemplateMapper.getTypeBySpId(spId);

        // 报警状态查询
        if (null != request.getAlarmStatus() &&  request.getAlarmStatus() != 0 ) {
            List<Integer> alarmStatus = new ArrayList<>();
            //1-报警 2-故障 3-离线 4-正常
            switch (request.getAlarmStatus()){
                case 1:
                    alarmStatus = Arrays.asList(2,3,6);
                    break;
                case 2:
                    alarmStatus = Collections.singletonList(4);
                    break;
                case 3:
                    alarmStatus = Collections.singletonList(0);
                    break;
                case 4:
                    alarmStatus = Collections.singletonList(1);
                    break;
                default:
                    break;
            }

            if (CollectionUtils.isEmpty(alarmStatus)) {
                queryWrapper.lambda().eq(Consumer::getId, null);
            } else {
                log.info("报警状态查询{},{}",spId, alarmStatus);
                List<Integer> consumerIds = deviceStateMapper.getConsumerIdsByDeviceStatus( spId, alarmStatus);
                log.info("报警状态查询consumerIds.size():{}",consumerIds.size());
                if (CollectionUtils.isEmpty(consumerIds)) {
                    queryWrapper.lambda().eq(Consumer::getId, null);
                }
                else {
                    queryWrapper.lambda().in(Consumer::getId, consumerIds);
                }
            }
        }

        if (CollectionUtil.isNotEmpty(request.getConsumerIdList())) {
            //勾选id查询
            queryWrapper.lambda().in(Consumer::getId, request.getConsumerIdList())
                    .eq(Consumer::getIsDeleted, IS_DELETED_FALSE)
                    .orderByDesc(Consumer::getUpdatedAt)
                    .eq(Consumer::getSpId, spId);
        } else {
            boolean isServiceSelect = false;
            //常规查询,精准查询
            List<Integer> consumerIdList = new ArrayList<>();
            if (request.getServiceStatus() != null && ConsumerServiceStatusEnum.getConsumerServiceStatusEnum(request.getServiceStatus()) != null) {
                isServiceSelect = true;
                QueryWrapper<ConsumerServiceInfo> consumerServiceInfoQueryWrapper = new QueryWrapper<>();
                if (request.getServiceStatus() == ConsumerServiceStatusEnum.CONSUMER_SERVICE_STATUS_1.getCode()) {
                    consumerServiceInfoQueryWrapper.lambda().gt(ConsumerServiceInfo::getEndDate, DateUtils.getDiffDate(DateUtils.today(), 30));
                }else if (request.getServiceStatus() == ConsumerServiceStatusEnum.CONSUMER_SERVICE_STATUS_2.getCode()) {
                    consumerServiceInfoQueryWrapper.lambda().le(ConsumerServiceInfo::getEndDate, DateUtils.getDiffDate(DateUtils.today(), 30))
                            .gt(ConsumerServiceInfo::getEndDate, DateUtils.getDiffDate(DateUtils.today(), 7));
                }else if (request.getServiceStatus() == ConsumerServiceStatusEnum.CONSUMER_SERVICE_STATUS_3.getCode()) {
                    consumerServiceInfoQueryWrapper.lambda().le(ConsumerServiceInfo::getEndDate, DateUtils.getDiffDate(DateUtils.today(), 7))
                            .gt(ConsumerServiceInfo::getEndDate, DateUtils.today());
                }else if (request.getServiceStatus() == ConsumerServiceStatusEnum.CONSUMER_SERVICE_STATUS_4.getCode()) {
                    consumerServiceInfoQueryWrapper.lambda().eq(ConsumerServiceInfo::getEndDate, DateUtils.today());
                }else if (request.getServiceStatus() == ConsumerServiceStatusEnum.CONSUMER_SERVICE_STATUS_5.getCode()) {
                    consumerServiceInfoQueryWrapper.lambda().lt(ConsumerServiceInfo::getEndDate, DateUtils.today())
                            .ge(ConsumerServiceInfo::getEndDate, DateUtils.getDiffDate(DateUtils.today(), -7));
                }else if (request.getServiceStatus() == ConsumerServiceStatusEnum.CONSUMER_SERVICE_STATUS_6.getCode()) {
                    consumerServiceInfoQueryWrapper.lambda().lt(ConsumerServiceInfo::getEndDate, DateUtils.getDiffDate(DateUtils.today(), -7));
                }
                consumerServiceInfoQueryWrapper.lambda().eq(ConsumerServiceInfo::getIsDeleted, IS_DELETED_FALSE)
                        .eq(ConsumerServiceInfo::getSpId, spId);
                List<ConsumerServiceInfo> consumerServiceInfoList = consumerServiceInfoService.list(consumerServiceInfoQueryWrapper);

                consumerIdList = consumerServiceInfoList.stream()
                        .map(ConsumerServiceInfo::getConsumerId).distinct().collect(Collectors.toList());
            }
            //是否存在 imei查询
            Dtu dtu = null;
            if (StringUtil.isNotEmpty(request.getImei())) {
                QueryWrapper<Dtu> dtuQueryWrapper = new QueryWrapper<>();
                dtuQueryWrapper.lambda().eq(Dtu::getIMEI, request.getImei())
                        .eq(Dtu::getIsDeleted, IS_DELETED_FALSE)
                        .eq(Dtu::getSpId, spId);
                dtu = dtuMapper.selectOne(dtuQueryWrapper);
                if (dtu != null && (!isServiceSelect || (isServiceSelect && consumerIdList.contains(dtu.getConsumerId())))) {
                    queryWrapper.lambda().eq(Consumer::getId, dtu.getConsumerId());
                }
                else {
                    queryWrapper.lambda().eq(Consumer::getId, null);
                }
            } else if (request.getServiceStatus() != null && ConsumerServiceStatusEnum.getConsumerServiceStatusEnum(request.getServiceStatus()) != null) {
                if (org.apache.commons.collections.CollectionUtils.isNotEmpty(consumerIdList)) {
                    queryWrapper.lambda().in(Consumer::getId, consumerIdList);
                }
                else {
                    queryWrapper.lambda().eq(Consumer::getId, null);
                }
            }
            //是否存在电磁阀
            if (request.getHasValve() != null) {
                QueryWrapper<Dtu> dtuQueryWrapper = new QueryWrapper<>();
                dtuQueryWrapper.lambda().eq(Dtu::getIsDeleted, IS_DELETED_FALSE).eq(Dtu::getSpId, spId)
                .ne(Dtu::getValveInfoId, 0);
                List<Dtu> dtus = dtuMapper.selectList(dtuQueryWrapper);
                List<Integer> consumerLists = dtus.stream().map(Dtu::getConsumerId).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(consumerLists)){
                    if (request.getHasValve() == 0){
                        queryWrapper.lambda().notIn(Consumer::getId, consumerLists);
                    }else {
                        queryWrapper.lambda().in(Consumer::getId, consumerLists);
                    }
                } else {
                    if (request.getHasValve() == 1){
                        queryWrapper.lambda().eq(Consumer::getId, null);
                    }
                }
            }
            // 设备类型+设备厂商
            if (StringUtil.isNotEmpty(request.getEquipmentType()) || StringUtil.isNotEmpty(request.getEquipmentManufacturer())) {
                QueryWrapper<Dtu> dtuQueryWrapper = new QueryWrapper<>();
                dtuQueryWrapper.lambda().eq(Dtu::getIsDeleted, IS_DELETED_FALSE).eq(Dtu::getSpId, spId);
                if (StringUtil.isNotEmpty(request.getEquipmentType())) {
                    dtuQueryWrapper.lambda().eq(Dtu::getEquipmentType, request.getEquipmentType());
                }
                if (StringUtil.isNotEmpty(request.getEquipmentManufacturer())) {
                    dtuQueryWrapper.lambda().eq(Dtu::getEquipmentManufacturer, request.getEquipmentManufacturer());
                }
                List<Dtu> dtus = dtuMapper.selectList(dtuQueryWrapper);
                List<Integer> consumerLists = dtus.stream().map(Dtu::getConsumerId).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(consumerLists)){
                    queryWrapper.lambda().in(Consumer::getId, consumerLists);
                } else {
                    queryWrapper.lambda().eq(Consumer::getId, null);
                }
            }
            if (StringUtils.isNotEmpty(request.getCustPhone())) {
                queryWrapper.lambda().and(i -> i.eq(Consumer::getCustPhone, request.getCustPhone()).or().eq(Consumer::getPhone, request.getCustPhone()));
            }
            queryWrapper.lambda().like(request.getConsumerName() != null, Consumer::getName, request.getConsumerName()) //客户名称
                    .like(StringUtil.isNotEmpty(request.getCustName()), Consumer::getCustName, request.getCustName())           // 户名
                    .like(StringUtil.isNotEmpty(request.getCustAddress()), Consumer::getCustAddress, request.getCustAddress())  //户址
                    //.eq(StringUtil.isNotEmpty(request.getCustPhone()), Consumer::getCustPhone, request.getCustPhone())       //户主手机号
                    //.or().eq(StringUtil.isNotEmpty(request.getCustPhone()), Consumer::getPhone, request.getCustPhone()) //户主手机号
                    .like(StringUtil.isNotEmpty(request.getSubsCode()), Consumer::getSubsCode, request.getSubsCode())         //户号
                    .in(CollectionUtil.isNotEmpty(request.getIndustryType()), Consumer::getIndustryType, request.getIndustryType()) //行业类型多选
                    .eq(StringUtil.isNotEmpty(request.getOrgCode()), Consumer::getOrgCode, request.getOrgCode())       //组织编码
                    .eq(StringUtil.isNotEmpty(request.getCustType()), Consumer::getCustType, request.getCustType())       //用户类型
                    .in(CollectionUtil.isNotEmpty(request.getCustTypes()), Consumer::getCustType, request.getCustTypes())       //用户类型多选中文
                    .like(StringUtil.isNotEmpty(request.getCustomerAddress()), Consumer::getCustomerAddress, request.getCustomerAddress())         //客户地址
                    .eq(Consumer::getIsDeleted, Constants.IS_DELETED_FALSE)
                    .and(request.getHasLongitudeAndLatitude() != null && request.getHasLongitudeAndLatitude() == 1, lqw -> {
                        lqw.isNotNull(Consumer::getPositionLat).or().isNotNull(Consumer::getPositionLon);
                    })
                    .and(request.getHasLongitudeAndLatitude() != null && request.getHasLongitudeAndLatitude() == 0, lqw -> {
                        lqw.isNull(Consumer::getPositionLat).isNull(Consumer::getPositionLon);
                    })
                    .orderByDesc(Consumer::getUpdatedAt)
                    .eq(Consumer::getSpId, spId);
            if (StringUtil.isNotEmpty(request.getCreateStartTime()) && StringUtil.isNotEmpty(request.getCreateEndTime())) {
                Date startTime = DateUtil.parse(request.getCreateStartTime());
                Date endTime = DateUtil.endOfDay(DateUtil.parse(request.getCreateEndTime()));
                queryWrapper.lambda().between(Consumer::getCreatedAt, startTime, endTime);
            }
            if (StringUtil.isNotEmpty(request.getVerificationStartTime()) && StringUtil.isNotEmpty(request.getVerificationEndTime())) {
                Date startTime = DateUtil.parse(request.getVerificationStartTime());
                Date endTime = DateUtil.endOfDay(DateUtil.parse(request.getVerificationEndTime()));
                queryWrapper.lambda().between(Consumer::getVerificationTime, startTime, endTime);
            }

            if( ObjectUtil.isNotEmpty(request.getFuncArea()) ){
                String inSql = "select consumerId from t_consumer_location cl where " +
                        " cl.sp_id = '"+spId+"'";
                if( null!= request.getFuncArea().getDistrictCode() ){
                    inSql += " AND cl.citycode = '"+request.getFuncArea().getDistrictCode()+"'";
                }
                if( null!= request.getFuncArea().getStreetCode() ){
                    inSql += " AND cl.adcode = '"+request.getFuncArea().getStreetCode()+"'";
                }
                if( null!= request.getFuncArea().getBusinessAreaCode() && FUNC_AREA_ALLOCAT_CUSTOM.equals(fieldTemplate.getFuncAreaAllocat()) ){
                    inSql += " AND cl.towncode = '"+request.getFuncArea().getBusinessAreaCode()+"'";
                }else if( null!= request.getFuncArea().getBusinessAreaCode() ){
                    inSql += " AND cl.township = '"+request.getFuncArea().getBusinessAreaCode()+"'";
                }
                queryWrapper.lambda().inSql(Consumer::getId, inSql);
            }

            page = PageHelper.startPage(request.getPage(), request.getPageSize());
        }
        List<Consumer> consumerList = consumerMapper.selectList(queryWrapper);
        ArrayList<ConsumerResponse> list = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(consumerList)) {
            List<String> spIds = new ArrayList<>();
            spIds.add(spId);
            //查询组织架构名称
            List<CompanyResponse> companyNameList = companyService.queryCompanyNameList(spIds);
            Map<String, String> companyNameMap = new HashMap<>();
            if (!CollectionUtils.isEmpty(companyNameList)) {
                companyNameMap = companyNameList.stream().collect(Collectors.toMap(CompanyResponse::getSpId, CompanyResponse::getName));
            }
            //批量查询字典
            List<DictionaryItemRespDTO> orgMapSubsCodeList = holder.getDictionaryByKey(ORG_MAP_SUBSCODE);
            Map<String, String> orgSubsCodeMap = new HashMap<>();
            if (!CollectionUtils.isEmpty(orgMapSubsCodeList)) {
                orgSubsCodeMap = orgMapSubsCodeList.stream().collect(Collectors.toMap(DictionaryItemRespDTO::getDescription, DictionaryItemRespDTO::getCompanyName));
            }
            //根据行业类型获得名字
            List<DictionaryItemRespDTO> industryType = holder.getIndustryTypeZJ();
            //获得客户id集合
            List<Integer> ids = consumerList.stream().map(Consumer::getId).collect(Collectors.toList());
            log.info("客户id集合: {}", ids.toString());

            //服务信息
            Map<Integer, LatestConsumerServiceSummaryResponse> map = consumerServiceInfoService.queryConsumerServiceInfoMap(ids);

            //获取服务区数据
            Map<Integer,ConsumerFuncAreaResponse> consumerFuncAreaMap = consumerLocationService.getConsumerFuncArea(
                    ids,
                    spId,
                    fieldTemplate.getFuncAreaAllocat()
            );

            //获取每个客户的最高级联系人
            List<Contacts> contactsList = contactsService.listByIds(ids, spId);
            Map<Integer, Contacts> contactsMap = new HashMap<>();
            if (!CollectionUtils.isEmpty(contactsList)) {
                contactsMap = contactsList.stream().collect(Collectors.toMap(Contacts::getConsumerId, Contacts -> Contacts, (a1, a2) -> a2));
            }
            for (Consumer consumer : consumerList) {

                ConsumerResponse consumerResponse = new ConsumerResponse();
                BeanUtil.copyProperties(consumer, consumerResponse);
                consumerResponse.setConsumerId(consumerResponse.getId());
                //对紫荆客户id增加前缀
                consumerResponse.setIdStr(consumerResponse.getId().toString());
                if (consumerResponse.getConsumerType().equals(CONSUMER_TYPE_ZJ)) {
                    consumerResponse.setIdStr(CONSUMER_ID_ZJ + consumerResponse.getId());
                }
                if (map.get(consumer.getId()) != null) {
                    consumerResponse.setNormalCount(map.get(consumer.getId()).getNormalCount());
                    consumerResponse.setUnexpiredLessThirtyCount(map.get(consumer.getId()).getUnexpiredLessThirtyCount());
                    consumerResponse.setUnexpiredLessSevenCount(map.get(consumer.getId()).getUnexpiredLessSevenCount());
                    consumerResponse.setPeriodCount(map.get(consumer.getId()).getPeriodCount());
                    consumerResponse.setExpiredLessSevenCount(map.get(consumer.getId()).getExpiredLessSevenCount());
                    consumerResponse.setExpiredMoreSevenCount(map.get(consumer.getId()).getExpiredMoreSevenCount());
                }
                consumerResponse.setCreatedAt(consumer.getCreatedAt());
                consumerResponse.setUpdatedAt(consumer.getUpdatedAt());
                if (StringUtils.isNotEmpty(consumer.getOrgCode()) && orgSubsCodeMap.containsKey(consumer.getOrgCode())) {
                    consumerResponse.setCompanyName(orgSubsCodeMap.get(consumer.getOrgCode()));
                } else {
                    if (companyNameMap.containsKey(consumer.getSpId())) {
                        consumerResponse.setCompanyName(companyNameMap.get(consumer.getSpId()));
                    }
                }
                for (DictionaryItemRespDTO dto : industryType) {
                    if (dto.getValue().equals(consumerResponse.getIndustryType())) {
                        consumerResponse.setIndustryType(dto.getName());
                    }
                }
                //关联的联系人数据
                if (contactsMap.containsKey(consumer.getId())) {
                    Contacts contacts = contactsMap.get(consumer.getId());
                    consumerResponse.setContactsName(contacts.getName());
                    consumerResponse.setContactsTelephone(contacts.getTelephone());
                }

                //客户经纬度

                if (consumerResponse.getPositionLon() != null && consumerResponse.getPositionLat() != null) {
                    consumerResponse.setPosition(consumerResponse.getPositionLon() + "," + consumerResponse.getPositionLat());
                }
                //客户来源
                consumerResponse.setSource(consumer.getSource() == 0 ? CONSUMER_SOURCE_SYSTEM:CONSUMER_SOURCE_ASST);

                if( null!=consumerFuncAreaMap && consumerFuncAreaMap.containsKey(consumer.getId())){
                    consumerResponse.setFuncArea(consumerFuncAreaMap.get(consumer.getId()));
                }

                list.add(consumerResponse);
            }
        }
        List<Integer> consumerIds= list.stream().map(ConsumerResponse::getConsumerId).collect(Collectors.toList());

        commonService.loadFieldAndPackaging(list, ConsumerResponse.class, consumerIds, null, null, spId,PageListCode.CUSTOMER_MANAGE.getCode());
        log.info("consumerList-list:{}", com.alibaba.fastjson.JSONObject.toJSONString(list));
        PageUtil<ConsumerResponse> pageUtil = new PageUtil<>();
        if (page != null) {
            pageUtil.setPage(request.getPage());
            pageUtil.setPageSize(request.getPageSize());
            pageUtil.setTotal(page.getTotal());
        } else {
            //非分页列表时,置0
            pageUtil.setPage(0);
            pageUtil.setPageSize(0);
            pageUtil.setTotal(request.getConsumerIdList().size());
        }
        pageUtil.setList(list);
        return pageUtil;
    }

    @Override
    public PageUtil<ConsumerResponse> consumerListAsst(ConsumerListRequest request) {
        String spId = ApplicationUtils.getWorkingSpId();
        if (!StringUtils.isEmpty(request.getSpId())) {
            spId = request.getSpId();
        }
        List<String> spIds = new ArrayList<>();
        spIds.add(spId);
        //查询组织架构名称
        List<CompanyResponse> companyNameList = companyService.queryCompanyNameList(spIds);
        Map<String, String> companyNameMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(companyNameList)) {
            companyNameMap = companyNameList.stream().collect(Collectors.toMap(CompanyResponse::getSpId, CompanyResponse::getName));
        }
        //批量查询字典
        List<DictionaryItemRespDTO> orgMapSubsCodeList = holder.getDictionaryByKey(ORG_MAP_SUBSCODE);
        Map<String, String> orgSubsCodeMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(orgMapSubsCodeList)) {
            orgSubsCodeMap = orgMapSubsCodeList.stream().collect(Collectors.toMap(DictionaryItemRespDTO::getDescription, DictionaryItemRespDTO::getCompanyName));
        }

        Page<Consumer> page = null;

        QueryWrapper<Consumer> queryWrapper = new QueryWrapper<>();
        //常规查询,精准查询
        //是否存在 imei查询
        if (StringUtil.isNotEmpty(request.getImei())) {
            QueryWrapper<Dtu> dtuQueryWrapper = new QueryWrapper<>();
            dtuQueryWrapper.lambda().eq(Dtu::getIMEI, request.getImei())
                    .eq(Dtu::getIsDeleted, IS_DELETED_FALSE)
                    .eq(Dtu::getSpId, spId);
            Dtu dtu = dtuMapper.selectOne(dtuQueryWrapper);
            ArrayList<Integer> consumerIdList = new ArrayList<>();
            if (dtu != null) {
                consumerIdList.add(dtu.getConsumerId());
                queryWrapper.lambda().in(Consumer::getId, consumerIdList);
            } else {
                queryWrapper.lambda().eq(Consumer::getId, null);
            }
        }
        if (null != request.getAlarmStatus() &&  request.getAlarmStatus() != 0 ) {
            List<Integer> alarmStatus = new ArrayList<>();
            //1-报警 2-故障 3-离线 4-正常
            switch (request.getAlarmStatus()){
                case 1:
                    alarmStatus = Arrays.asList(2,3,6);
                    break;
                case 2:
                    alarmStatus = Collections.singletonList(4);
                    break;
                case 3:
                    alarmStatus = Collections.singletonList(0);
                    break;
                case 4:
                    alarmStatus = Collections.singletonList(1);
                    break;
                default:
                    break;
            }

            if (CollectionUtils.isEmpty(alarmStatus)) {
                queryWrapper.lambda().eq(Consumer::getId, null);
            } else {
               List<Integer> consumerIds = deviceStateMapper.getConsumerIdsByDeviceStatus( spId, alarmStatus);
               if (CollectionUtils.isEmpty(consumerIds)) {
                   queryWrapper.lambda().eq(Consumer::getId, null);
               }
               else {
                   queryWrapper.lambda().in(Consumer::getId, consumerIds);
               }
            }
        }
        if (StringUtils.isNotEmpty(request.getOrgCode())) {
            queryWrapper.lambda().eq(Consumer::getOrgCode, request.getOrgCode());
        }
        if (StringUtils.isNotEmpty(request.getCustType())) {
            queryWrapper.lambda().eq(Consumer::getCustType, request.getCustType());
        }
        if (CollectionUtil.isNotEmpty(request.getCustTypes())) {
            queryWrapper.lambda().eq(Consumer::getCustType, request.getCustTypes());
        }
        // 设备类型+设备厂商
        if (StringUtil.isNotEmpty(request.getEquipmentType()) || StringUtil.isNotEmpty(request.getEquipmentManufacturer())) {
            QueryWrapper<Dtu> dtuQueryWrapper = new QueryWrapper<>();
            dtuQueryWrapper.lambda().eq(Dtu::getIsDeleted, IS_DELETED_FALSE).eq(Dtu::getSpId, spId);
            if (StringUtil.isNotEmpty(request.getEquipmentType())) {
                dtuQueryWrapper.lambda().eq(Dtu::getEquipmentType, request.getEquipmentType());
            }
            if (StringUtil.isNotEmpty(request.getEquipmentManufacturer())) {
                dtuQueryWrapper.lambda().eq(Dtu::getEquipmentManufacturer, request.getEquipmentManufacturer());
            }
            List<Dtu> dtus = dtuMapper.selectList(dtuQueryWrapper);
            List<Integer> consumerLists = dtus.stream().map(Dtu::getConsumerId).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(consumerLists)){
                queryWrapper.lambda().in(Consumer::getId, consumerLists);
            } else {
                queryWrapper.lambda().eq(Consumer::getId, null);
            }
        }

        queryWrapper.lambda().eq(StringUtil.isNotEmpty(request.getPhone()), Consumer::getPhone, request.getPhone())
                .eq(StringUtil.isNotEmpty(request.getMemberId()), Consumer::getMemberId, request.getMemberId())
                .like(StringUtil.isNotEmpty(request.getCustomerAddress()), Consumer::getCustomerAddress, request.getCustomerAddress())
                .eq(Consumer::getSpId, spId)
                .eq(Consumer::getIsDeleted, IS_DELETED_0)
                .and(request.getHasLongitudeAndLatitude() != null && request.getHasLongitudeAndLatitude() == 1, lqw -> {
                    lqw.isNotNull(Consumer::getPositionLat).or().isNotNull(Consumer::getPositionLon);
                })
                .and(request.getHasLongitudeAndLatitude() != null && request.getHasLongitudeAndLatitude() == 0, lqw -> {
                    lqw.isNull(Consumer::getPositionLat).isNull(Consumer::getPositionLon);
                })
                .orderByDesc(Consumer::getUpdatedAt);
        page = PageHelper.startPage(request.getPage(), request.getPageSize());
        List<Consumer> consumerList = this.list(queryWrapper);
        List<ConsumerResponse> list = BeanConvertUtils.convertListTo(consumerList, ConsumerResponse::new);
        //客户经纬度
        for (ConsumerResponse response : list) {
            if (response.getPositionLon() != null && response.getPositionLat() != null) {
                response.setPosition(response.getPositionLon() + "," + response.getPositionLat());
            }
            if (StringUtils.isNotEmpty(response.getOrgCode()) && orgSubsCodeMap.containsKey(response.getOrgCode())) {
                response.setCompanyName(orgSubsCodeMap.get(response.getOrgCode()));
            } else {
                if (companyNameMap.containsKey(response.getSpId())) {
                    response.setCompanyName(companyNameMap.get(response.getSpId()));
                }
            }
        }
        List<DictionaryItemRespDTO> industryType = holder.getIndustryTypeZJ();
        for (ConsumerResponse response : list) {
            for (DictionaryItemRespDTO dto : industryType) {
                if (dto.getValue().equals(response.getIndustryType())) {
                    response.setIndustryType(dto.getName());
                }
            }
            response.setIdStr(response.getId().toString());
            if (response.getConsumerType().equals(CONSUMER_TYPE_ZJ)) {
                response.setIdStr(CONSUMER_ID_ZJ + response.getId());
            }
        }
        PageUtil<ConsumerResponse> pageUtil = new PageUtil<>();
        pageUtil.setPage(request.getPage());
        pageUtil.setPageSize(request.getPageSize());
        pageUtil.setTotal(page.getTotal());
        pageUtil.setList(list);
        return pageUtil;
    }

    @Override
    public ConsumerDetailResponse detail(String consumerId) {
        String spId = ApplicationUtils.getWorkingSpId();
        //组织关系
        List<String> spIds = organizationService.getSpIds(spId);

        ConsumerDetailResponse consumerDetailResponse = new ConsumerDetailResponse();
        //判断该客户是否存在
        QueryWrapper<Consumer> consumerWrapper = new QueryWrapper<>();
        consumerWrapper.lambda().eq(Consumer::getId, consumerId)
                .eq(Consumer::getIsDeleted, Constants.IS_DELETED_FALSE)
                .in(Consumer::getSpId, spIds);
        Consumer consumer = this.getOne(consumerWrapper);
        if (consumer == null) {
            throw new BizException("该客户id不存在!");
        }
        ConsumerResponse consumerResponse = new ConsumerResponse();
        BeanUtil.copyProperties(consumer, consumerResponse);
        //查询组织架构名称
        List<CompanyResponse> companyNameList = companyService.queryCompanyNameList(spIds);
        Map<String, String> companyNameMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(companyNameList)) {
            companyNameMap = companyNameList.stream().collect(Collectors.toMap(CompanyResponse::getSpId, CompanyResponse::getName));
        }
        //批量查询字典
        List<DictionaryItemRespDTO> orgMapSubsCodeList = holder.getDictionaryByKey(ORG_MAP_SUBSCODE);
        Map<String, String> orgSubsCodeMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(orgMapSubsCodeList)) {
            orgSubsCodeMap = orgMapSubsCodeList.stream().collect(Collectors.toMap(DictionaryItemRespDTO::getDescription, DictionaryItemRespDTO::getCompanyName));
        }
        if (consumer.getPkgId() != null && consumer.getPkgId() > 0) {
            //判断该客户是否存在
            ServicePkgRecord servicePkgRecord = servicePkgRecordMapper.selectById(consumer.getPkgId());
            if (servicePkgRecord != null) {
                consumerResponse.setPkgName(servicePkgRecord.getPgkName());
            }
        }

        //客户的设备状态
        consumerResponse.setStatusAnyalert(false);
        consumerResponse.setStatusAnybroken(false);
        consumerResponse.setStatusAnyoffline(false);
        consumerResponse.setStatusAnynormal(true);
        if (StringUtils.isNotEmpty(consumer.getOrgCode()) && orgSubsCodeMap.containsKey(consumer.getOrgCode())) {
            consumerResponse.setCompanyName(orgSubsCodeMap.get(consumer.getOrgCode()));
        } else {
            if (companyNameMap.containsKey(consumer.getSpId())) {
                consumerResponse.setCompanyName(companyNameMap.get(consumer.getSpId()));
            }
        }
        QueryWrapper<Dtu> dtuQueryWrapper = new QueryWrapper<>();
        dtuQueryWrapper.lambda().eq(Dtu::getConsumerId, consumer.getId())
                .eq(Dtu::getIsDeleted, Constants.IS_DELETED_FALSE)
                .eq(Dtu::getSpId, consumer.getSpId());
        List<Dtu> dtuList = dtuMapper.selectList(dtuQueryWrapper);
        int sum = 0;
        for (Dtu dtu : dtuList) {
            LatestLog latestLog = latestLogService.get(dtu.getIMEI(), dtu.getSpId());
            //设备状态 0:离线 1:正常 2:低报 3:高报 4:故障
            if (latestLog.getEquipmentStatus().equals(0)) {
                consumerResponse.setStatusAnyoffline(true);
                sum++;
            } else if (latestLog.getEquipmentStatus().equals(2) || latestLog.getEquipmentStatus().equals(3) || latestLog.getEquipmentStatus().equals(6)) {
                consumerResponse.setStatusAnyalert(true);
            } else if (latestLog.getEquipmentStatus().equals(4)) {
                consumerResponse.setStatusAnybroken(true);
            }
        }
        if (sum == dtuList.size()) {
            consumerResponse.setStatusAnynormal(false);
        }
        //客户字典
        List<DictionaryItemRespDTO> dictionary = holder.getIndustryTypeZJ();
        for (DictionaryItemRespDTO dto : dictionary) {
            if (dto.getValue().equals(consumer.getIndustryType())) consumerResponse.setIndustryTypeName(dto.getName());
        }
        log.info("客户基本信息:{}", consumer.toString());

        //获取联系人列表
        QueryWrapper<Contacts> contactsWrapper = new QueryWrapper<>();
        contactsWrapper.lambda().eq(Contacts::getConsumerId, consumerId)
                .eq(Contacts::getIsDeleted, Constants.IS_DELETED_FALSE)
                .in(Contacts::getSpId, consumer.getSpId())
                .orderByAsc(Contacts::getLevel)
                .orderByDesc(Contacts::getUpdatedAt);
        List<Contacts> contactsList = contactsService.list(contactsWrapper);
        List<ContactsResponse> contactsResponseList = BeanConvertUtils.convertListTo(contactsList, ContactsResponse::new);
        //级别名称
        for (ContactsResponse contactsResponse : contactsResponseList) {
            if (contactsResponse.getLevel() != null) {
                DictionaryItemRespDTO communicationModeDict = holder.getDictionaryByKey(
                        Constants.CONTACT_LEVEL).stream().filter(a -> a.getValue().equals(
                        contactsResponse.getLevel().toString())).collect(Collectors.toList()).get(0);
                contactsResponse.setLevelName(communicationModeDict.getName());
            }
        }
        //C端绑定情况
        QueryWrapper<CustomerSubs> customerSubsQueryWrapper = new QueryWrapper<>();
        customerSubsQueryWrapper.lambda().eq(CustomerSubs::getSubsCode, consumerResponse.getSubsCode())
                .eq(CustomerSubs::getBandingStatus, 1)
                .eq(CustomerSubs::getIsDeleted, Constants.IS_DELETED_FALSE)
                .eq(CustomerSubs::getSpId, consumer.getSpId());
        List<CustomerSubs> customerSubsList = customerSubsService.list(customerSubsQueryWrapper);
        if (!customerSubsList.isEmpty()) {
            consumerDetailResponse.setClientBindStatus(1);
        } else {
            consumerDetailResponse.setClientBindStatus(0);
        }

        FieldTemplate fieldTemplate = fieldTemplateMapper.getTypeBySpId(spId);
        Map<Integer,ConsumerFuncAreaResponse> consumerFuncAreaMap = consumerLocationService.getConsumerFuncArea(
                Arrays.asList(consumer.getId()),
                spId,
                fieldTemplate.getFuncAreaAllocat()
        );
        if( null!=consumerFuncAreaMap && consumerFuncAreaMap.containsKey(consumer.getId())){
            consumerResponse.setFuncArea(consumerFuncAreaMap.get(consumer.getId()));
        }

        //获取工单的客户类型
        int orderCustType = workOrderHistoryService.getOrderLaunchCustType(consumer);
        consumerResponse.setOrderCustType(orderCustType);

        //数据合并
        consumerDetailResponse.setConsumerResponse(consumerResponse);
        consumerDetailResponse.setContactsResponseList(contactsResponseList);
        return consumerDetailResponse;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer addConsumer(ConsumerRequest request) {
        String spId = ApplicationUtils.getWorkingSpId();
        //校验
        if (CollectionUtil.isNotEmpty(request.getContactsList())) {
            List<String> telephoneList = request.getContactsList().stream().map(ContactsRequest::getTelephone).collect(Collectors.toList());
            boolean isRepeat = telephoneList.size() != new HashSet<String>(telephoneList).size();
            if (isRepeat) {
                throw new BizException("同联系人电话请勿重复填写.");
            }
            for (ContactsRequest contactsRequest : request.getContactsList()) {
                if (StringUtil.isEmpty(contactsRequest.getName()) ||
                        StringUtil.isEmpty(contactsRequest.getTelephone()) ||
                        contactsRequest.getLevel() == null) {
                    throw new BizException("联系人信息请填写完整!");
                }
            }
        }
        //校验户号是否已存在
        if (StringUtil.isNotEmpty(request.getSubsCode())) {
            if (request.getType() == 2 && StringUtils.isBlank(request.getOrgCode())) {
                throw new BizException("户号对应组织机构不存在");
            }
            QueryWrapper<Consumer> consumerWrapper = new QueryWrapper<>();
            consumerWrapper.lambda().eq(Consumer::getSubsCode, request.getSubsCode())
                    .eq(Consumer::getIsDeleted, Constants.IS_DELETED_FALSE)
                    .eq(Consumer::getSpId, spId);
            Consumer one = this.getOne(consumerWrapper);
            if (one != null) {
                throw new BizException("该户号已经创建客户.");
            }
        }
        //校验服务套餐是否为必填
        if (request.getPkgId() == null || request.getPkgId() == 0) {
            BusinessNotice noticeServiceByCode = businessNoticeService.getByCode(DIFFERENT_SERVICE_PACKAGE_MODE, spId);
            if (noticeServiceByCode != null && "ON".equals(noticeServiceByCode.getParamValue())) {
                throw new BizException("客户套餐开启时为必填");
            }
        }

        if (request.getPkgId() != null && request.getPkgId() > 0) {
            ServicePkgRecord servicePkgRecord = servicePkgRecordMapper.selectById(request.getPkgId());
            if (servicePkgRecord != null) {
                request.setPkgName(servicePkgRecord.getPgkName());
            }
        }

        Consumer consumerAdd = new Consumer();
        BeanUtil.copyProperties(request, consumerAdd);
        consumerAdd.setConsumerSeq("0");
        consumerAdd.setOrgCode(request.getOrgCode());

        //spId，去department表里查
        QueryWrapper<Department> departmentQueryWrapper = new QueryWrapper<>();
        departmentQueryWrapper.lambda().eq(Department::getSpId, spId);
        Department department = departmentMapper.selectOne(departmentQueryWrapper);
        if (StringUtil.isEmpty(request.getName())) {
            consumerAdd.setName(Constants.STR_EMPTY);
        }
        consumerAdd.setDepartmentId(department.getId());
        consumerAdd.setPath(department.getPath());
        consumerAdd.setSpId(spId);
        consumerAdd.setStatusAnyalert(false);
        consumerAdd.setStatusAnybroken(false);
        consumerAdd.setStatusAnyoffline(false);
        consumerAdd.setStatusAnynormal(true);
        consumerAdd.setStatusUpdatetime(new Date());
        consumerAdd.setTemplateType(0);
        // 优化，在客户新增的时候，给字段company_code赋值 规则如下
        // 企业代码：
        //3位数字，从101开始编号。
        //保留位：
        //2为数字，0默认值。
        //年份：
        //年份用2位数字表示
        //年份使用4位年份的后2位数字，例：2019年用19表示
        //月份：
        //月份用2位数字表示，01至12
        //流水号：
        //顺序号范围，00001~99999
        StringBuilder companyCodeStr = new StringBuilder();
        QueryWrapper<CompanyCode> codeQueryWrapper = new QueryWrapper<>();
        codeQueryWrapper.lambda().eq(CompanyCode::getSpId, spId).eq(CompanyCode::getIsDeleted, 0);
        CompanyCode companyCode = companyCodeMapper.selectOne(codeQueryWrapper);
        if (companyCode != null) {
            companyCodeStr.append(companyCode.getCompanyCode());
        } else {
            companyCodeStr.append("000");
        }
        companyCodeStr.append("00");
        // 获取当前年的后两位
        String yy = new SimpleDateFormat("yy", Locale.CHINESE).format(new Date());
        // 获取当钱月份
        String mm = new SimpleDateFormat("MM", Locale.CHINESE).format(new Date());
        companyCodeStr.append(yy).append(mm);
        counter++;
        String format = String.format("%05d", counter);
        companyCodeStr.append(format);
        log.info("客户企业代码:{}", companyCodeStr.toString());
        consumerAdd.setCompanyCode(companyCodeStr.toString());
        this.save(consumerAdd);
        log.info("新增客户为:{}", consumerAdd);

        //更新用户地理位置信息
        FieldTemplate fieldTemplate = fieldTemplateMapper.getTypeBySpId(spId);
        if( Constants.FUNC_AREA_ALLOCAT_CUSTOM.equals(fieldTemplate.getFuncAreaAllocat()) ){
            consumerLocationService.updateConsumerLocationCustom(consumerAdd,request.getFuncArea());
        }else{
            consumerLocationService.updateConsumerLocation(consumerAdd);
        }

        //新增客户绑定的联系人
        List<Contacts> contactsList = BeanConvertUtils.convertListTo(request.getContactsList(), Contacts::new);
        for (Contacts contacts : contactsList) {
            contacts.setSpId(spId);
            contacts.setConsumerId(consumerAdd.getId());
        }
        contactsService.saveBatch(contactsList);

        //企业级操作日志
        StringBuilder detail = new StringBuilder();
        detail.append(logUtil.addOrDeleteEntity(consumerAdd, Consumer.class));
        for (Contacts contacts : contactsList) {
            detail.append("\n");
            detail.append(logUtil.addOrDeleteEntity(contacts, Contacts.class));
        }
        LogVO vo = new LogVO();
        vo.setDetail(detail.toString());
        List<Consumer> consumers = new ArrayList<>();
        consumers.add(consumerAdd);
        vo.setCommonInfo(getCustomInfo(consumers));
        LogRecordAspect.threadLocal.set(vo);

        //操作日志log
        OperationLogVO logVO = new OperationLogVO();
        List<Integer> codeList = new ArrayList<>();
        codeList.add(OperationTypeEnum.OPERATION_TYPE_1.getCode());
        logVO.setCodeList(codeList);
        logVO.setTableName(TableConst.consumer.name());
        logVO.setTableKey(consumerAdd.getId().toString());
        operationLogService.insertLog(logVO);


        return consumerAdd.getId();

    }

    @Transactional(rollbackFor = Exception.class)
    public Integer addConsumer(ConsumerRequest request,String spId) {
        if (StringUtils.isEmpty(spId)){
            spId = ApplicationUtils.getWorkingSpId();
        }
        //校验
        if (CollectionUtil.isNotEmpty(request.getContactsList())) {
            List<String> telephoneList = request.getContactsList().stream().map(ContactsRequest::getTelephone).collect(Collectors.toList());
            boolean isRepeat = telephoneList.size() != new HashSet<String>(telephoneList).size();
            if (isRepeat) {
                throw new BizException("同联系人电话请勿重复填写.");
            }
            for (ContactsRequest contactsRequest : request.getContactsList()) {
                if (StringUtil.isEmpty(contactsRequest.getName()) ||
                        StringUtil.isEmpty(contactsRequest.getTelephone()) ||
                        contactsRequest.getLevel() == null) {
                    throw new BizException("联系人信息请填写完整!");
                }
            }
        }
        //校验户号是否已存在
        if (StringUtil.isNotEmpty(request.getSubsCode())) {
            if (request.getType() == 2 && StringUtils.isBlank(request.getOrgCode())) {
                throw new BizException("户号对应组织机构不存在");
            }
            QueryWrapper<Consumer> consumerWrapper = new QueryWrapper<>();
            consumerWrapper.lambda().eq(Consumer::getSubsCode, request.getSubsCode())
                    .eq(Consumer::getIsDeleted, Constants.IS_DELETED_FALSE)
                    .eq(Consumer::getSpId, spId);
            Consumer one = this.getOne(consumerWrapper);
            if (one != null) {
                throw new BizException("该户号已经创建客户.");
            }
        }


        Consumer consumerAdd = new Consumer();
        BeanUtil.copyProperties(request, consumerAdd);
        consumerAdd.setConsumerSeq("0");
        if ( null == request.getOrgCode() ){
            consumerAdd.setOrgCode("");
        }else{
            consumerAdd.setOrgCode(request.getOrgCode());
        }

        //spId，去department表里查
        QueryWrapper<Department> departmentQueryWrapper = new QueryWrapper<>();
        departmentQueryWrapper.lambda().eq(Department::getSpId, spId);
        Department department = departmentMapper.selectOne(departmentQueryWrapper);
        if (StringUtil.isEmpty(request.getName())) {
            consumerAdd.setName(Constants.STR_EMPTY);
        }
        consumerAdd.setDepartmentId(department.getId());
        consumerAdd.setPath(department.getPath());
        consumerAdd.setSpId(spId);
        consumerAdd.setStatusAnyalert(false);
        consumerAdd.setStatusAnybroken(false);
        consumerAdd.setStatusAnyoffline(false);
        consumerAdd.setStatusAnynormal(true);
        consumerAdd.setStatusUpdatetime(new Date());
        consumerAdd.setTemplateType(0);
        // 优化，在客户新增的时候，给字段company_code赋值 规则如下
        // 企业代码：
        //3位数字，从101开始编号。
        //保留位：
        //2为数字，0默认值。
        //年份：
        //年份用2位数字表示
        //年份使用4位年份的后2位数字，例：2019年用19表示
        //月份：
        //月份用2位数字表示，01至12
        //流水号：
        //顺序号范围，00001~99999
        StringBuilder companyCodeStr = new StringBuilder();
        QueryWrapper<CompanyCode> codeQueryWrapper = new QueryWrapper<>();
        codeQueryWrapper.lambda().eq(CompanyCode::getSpId, spId).eq(CompanyCode::getIsDeleted, 0);
        CompanyCode companyCode = companyCodeMapper.selectOne(codeQueryWrapper);
        if (companyCode != null) {
            companyCodeStr.append(companyCode.getCompanyCode());
        } else {
            companyCodeStr.append("000");
        }
        companyCodeStr.append("00");
        // 获取当前年的后两位
        String yy = new SimpleDateFormat("yy", Locale.CHINESE).format(new Date());
        // 获取当钱月份
        String mm = new SimpleDateFormat("MM", Locale.CHINESE).format(new Date());
        companyCodeStr.append(yy).append(mm);
        counter++;
        String format = String.format("%05d", counter);
        companyCodeStr.append(format);
        log.info("客户企业代码:{}", companyCodeStr.toString());
        consumerAdd.setCompanyCode(companyCodeStr.toString());
        this.save(consumerAdd);
        log.info("新增客户为:{}", consumerAdd);

        //更新客户地址相关信息
        if( FUNC_AREA_ALLOCAT_CUSTOM.equals(request.getFuncAreaAllocat()) ){
            consumerLocationService.updateConsumerLocationCustom(consumerAdd, request.getFuncArea());
        }else{
            consumerLocationService.updateConsumerLocation(consumerAdd);
        }

        //新增客户绑定的联系人
        List<Contacts> contactsList = BeanConvertUtils.convertListTo(request.getContactsList(), Contacts::new);
        for (Contacts contacts : contactsList) {
            contacts.setSpId(spId);
            contacts.setConsumerId(consumerAdd.getId());
        }
        contactsService.saveBatch(contactsList);

        //企业级操作日志
        StringBuilder detail = new StringBuilder();
        detail.append(logUtil.addOrDeleteEntity(consumerAdd, Consumer.class));
        for (Contacts contacts : contactsList) {
            detail.append("\n");
            detail.append(logUtil.addOrDeleteEntity(contacts, Contacts.class));
        }
        LogVO vo = new LogVO();
        vo.setDetail(detail.toString());
        List<Consumer> consumers = new ArrayList<>();
        consumers.add(consumerAdd);
        vo.setCommonInfo(getCustomInfo(consumers));
        LogRecordAspect.threadLocal.set(vo);

        //操作日志log
        OperationLogVO logVO = new OperationLogVO();
        List<Integer> codeList = new ArrayList<>();
        codeList.add(OperationTypeEnum.OPERATION_TYPE_1.getCode());
        logVO.setCodeList(codeList);
        logVO.setTableName(TableConst.consumer.name());
        logVO.setTableKey(consumerAdd.getId().toString());
        operationLogService.insertLog(logVO);


        return consumerAdd.getId();

    }

    private String getCustomInfo(List<Consumer> consumers) {
        StringBuilder stringBuilder = new StringBuilder();
        for (Consumer consumer : consumers) {
            stringBuilder.append("客户ID：").append(consumer.getId()).append("\n");
            if (StringUtils.isNotEmpty(consumer.getSubsCode())){
                stringBuilder.append("户号：").append(consumer.getSubsCode()).append("\n");
            }
            if (StringUtils.isNotEmpty(consumer.getCustName())){
                stringBuilder.append("户名：").append(consumer.getCustName()).append("\n");
            }
            if (StringUtils.isNotEmpty(consumer.getName())){
                stringBuilder.append("客户名称：").append(consumer.getName()).append("\n");
            }
        }
        stringBuilder.deleteCharAt(stringBuilder.length() -1);
        return stringBuilder.toString();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteConsumer(String consumerId) {
        String spId = ApplicationUtils.getWorkingSpId();

        //判断是否存在绑定的设备
        QueryWrapper<Dtu> dtuQueryWrapper = new QueryWrapper<>();
        dtuQueryWrapper.lambda().eq(Dtu::getConsumerId, Integer.valueOf(consumerId))
                .eq(Dtu::getSpId, spId)
                .eq(Dtu::getIsDeleted, Constants.IS_DELETED_FALSE);
        List<Dtu> dtuList = equipmentService.list(dtuQueryWrapper);
        if (CollectionUtil.isNotEmpty(dtuList)) {
            throw new BizException("请先解绑设备");
        }
        QueryWrapper<Consumer> consumerQueryWrapper = new QueryWrapper<>();
        consumerQueryWrapper.lambda().eq(Consumer::getId, consumerId)
                .eq(Consumer::getIsDeleted, Constants.IS_DELETED_FALSE)
                .eq(Consumer::getSpId, spId);
        List<Consumer> consumers = consumerMapper.selectList(consumerQueryWrapper);
        if (!CollectionUtils.isEmpty(consumers)&&consumers.get(0).getStatus()==1)  throw new BizException("工单进行中，客户信息不可修改");
        if (!CollectionUtils.isEmpty(consumers))workOrderHistoryService.existWorkOrder(consumers.get(0).getSubsCode(),spId);
        // 客户表删除
        Consumer consumer = new Consumer();
        consumer.setId(Integer.valueOf(consumerId));
        consumer.setIsDeleted(true);
        this.updateById(consumer);

        //联系人表删除
        QueryWrapper<Contacts> contactsWrapper = new QueryWrapper<>();
        contactsWrapper.lambda().eq(Contacts::getConsumerId, consumerId)
                .eq(Contacts::getSpId, spId)
                .eq(Contacts::getIsDeleted, Constants.IS_DELETED_FALSE);
        Contacts contacts = new Contacts();
        contacts.setIsDeleted(true);
        contactsService.update(contacts, contactsWrapper);
        //解除 设备与客户的关联
        Dtu dtuUpdate = new Dtu();
        dtuUpdate.setConsumerId(0);
        dtuUpdate.setInstallationPosition(Constants.STR_EMPTY);
        dtuUpdate.setName(Constants.STR_EMPTY);

        List<String> imeiList = dtuList.stream().map(Dtu::getIMEI).collect(Collectors.toList());
        equipmentService.update(dtuUpdate, dtuQueryWrapper);  //修改dtu表,客户id,name,安装位置

        if (CollectionUtil.isNotEmpty(imeiList)) {
            QueryWrapper<DtuAep> aepWrapper = new QueryWrapper<>();
            aepWrapper.lambda().in(DtuAep::getIMEI, imeiList)
                    .eq(DtuAep::getSpId, spId)
                    .eq(DtuAep::getIsDeleted, Constants.IS_DELETED_FALSE);
            DtuAep dtuAep = new DtuAep();
            dtuAep.setOpenStatus(0);
            dtuAep.setOpenTime(Constants.STR_EMPTY);
            dtuAepMapper.update(dtuAep, aepWrapper);

            //批量新增设备解绑记录
            ArrayList<ConsumerDtuHistory> historyList = new ArrayList<>();
            for (Dtu dtu : dtuList) {
                if (!EquipmentType.POINT_TYPE_GAS_DETECTOR.getCode().equals(dtu.getEquipmentType())) {
                    ConsumerDtuHistory history = new ConsumerDtuHistory();
                    history.setId(null);
                    history.setDeviceId(dtu.getId());
                    history.setEvent(0);
                    history.setIMEI(dtu.getIMEI());
                    history.setConsumerId(consumer.getId());
                    history.setOperationPersonCode(ApplicationUtils.getWorkingUser().getUsername());
                    history.setOperationPersonName(ApplicationUtils.getWorkingUser().getName());
                    history.setRemark(STR_EMPTY);
                    history.setSpId(ApplicationUtils.getWorkingSpId());
                    historyList.add(history);
                    //删除服务信息
                    consumerServiceInfoService.deleteConsumerServiceInfo(dtu.getIMEI());
                }
            }
            consumerDtuHistoryService.saveBatch(historyList);
        }

        // 客户地址信息表删除
        consumerLocationService.deleteConsumerLocation(spId,Integer.valueOf(consumerId));
        // 更新设备信息
        consumerLocationService.updateConsumerLocationDeviceNum(spId,Integer.valueOf(consumerId));

        // 报警策略,客户移除
        // 策略对象包含该consumerId的策略
        QueryWrapper<WarnStrategy> strategyQueryWrapper = new QueryWrapper<>();
        strategyQueryWrapper.lambda().eq(WarnStrategy::getStrategyObj, 2)
                .eq(WarnStrategy::getIsDeleted, Constants.IS_DELETED_FALSE)
                .eq(WarnStrategy::getSpId, spId)
                .like(WarnStrategy::getStrategyObjValues, consumerId + ";");
        //会有冗余的数据被查到
        List<WarnStrategy> warnStrategyList = warnStrategyService.list(strategyQueryWrapper);
        if (CollectionUtil.isNotEmpty(warnStrategyList)) {
            //遍历,移除该策略对象
            Iterator<WarnStrategy> iterator = warnStrategyList.iterator();
            while (iterator.hasNext()) {
                WarnStrategy warnStrategy = iterator.next();
                String objValues = warnStrategy.getStrategyObjValues();
                String[] consumerIds = objValues.split(";");
                List<String> list = Arrays.asList(consumerIds);
                ArrayList<String> newList = new ArrayList<>();
                for (int i = 0; i < list.size(); i++) {
                    if (!list.get(i).equals(consumerId)) {
                        newList.add(list.get(i));
                    }
                }
                // 当发现冗余数据被查询,移除要更新的数据
                if (newList.size() == list.size()) {
                    iterator.remove();
                    continue;
                }
                //当该策略对象只剩当前 客户id时,策略失效
                if (CollectionUtil.isEmpty(newList)) {
                    warnStrategy.setIsDisabled(2);
                } else {
                    String newObjValues = String.join(";", newList);
                    log.info("warnStrategyId = {}, 更新后的策略对象为:{}", warnStrategy.getId(), newObjValues);
                    warnStrategy.setStrategyObjValues(newObjValues);
                }

            }
            //更新
            warnStrategyService.updateBatchById(warnStrategyList);

        }

        //平台操作日志log
        OperationLogVO logVO = new OperationLogVO();
        List<Integer> logCodeList = new ArrayList<>();
        logCodeList.add(OperationTypeEnum.OPERATION_TYPE_5.getCode());
        logVO.setCodeList(logCodeList);
        logVO.setTableName(TableConst.consumer.name());
        logVO.setTableKey(consumerId);
        operationLogService.insertLog(logVO);
    }
    public String getCustomInfoByIds(List<String> consumerList) {
        LambdaQueryWrapper<Consumer> lqw = new LambdaQueryWrapper<>();
        lqw.in(Consumer::getId, consumerList);
        List<Consumer> list = this.list(lqw);
        String customInfo = this.getCustomInfo(list);
        return customInfo;
    }
    public String getCustomInfo(String consumerId) {
        LambdaQueryWrapper<Consumer> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Consumer::getId, consumerId);
        Consumer one = this.getOne(lqw);
        List<Consumer> consumers = new ArrayList<>();
        consumers.add(one);
        String customInfo = this.getCustomInfo(consumers);
        return customInfo;
    }

    @Override
    @Transactional
    public String editConsumer(ConsumerRequest request) {
        String spId = ApplicationUtils.getWorkingSpId();
        //行业发生改变
        QueryWrapper<Consumer> queryOldWrapper = new QueryWrapper<>();
        queryOldWrapper.lambda().eq(Consumer::getId, request.getId())
                .eq(Consumer::getIsDeleted, Constants.IS_DELETED_FALSE)
                .eq(Consumer::getSpId, spId);
        Consumer consumerOld = this.getOne(queryOldWrapper);
        if (!StringUtils.isBlank(consumerOld.getSubsCode())
                && !consumerOld.getSubsCode().equals(request.getSubsCode())&&consumerOld.getSource()==1)
            throw new BizException("销售安装工单生成的燃气户信息不可修改");
        if (consumerOld!=null&&consumerOld.getStatus()==1)  throw new BizException("工单进行中，客户信息不可修改");
        if (consumerOld!=null&&consumerOld.getStatus()==1
                &&!request.getSubsCode().equals(consumerOld.getSubsCode()))
            throw new BizException("销售安装工单生成的燃气户信息不可修改");
        //校验户号是否已存在
        if (StringUtil.isNotEmpty(request.getSubsCode())) {
            QueryWrapper<Consumer> consumerWrapper = new QueryWrapper<>();
            consumerWrapper.lambda().eq(Consumer::getSubsCode, request.getSubsCode())
                    .eq(Consumer::getIsDeleted, Constants.IS_DELETED_FALSE)
                    .eq(Consumer::getSpId, spId);
            Consumer one = this.getOne(consumerWrapper);
            if (one != null && !consumerOld.getId().equals(one.getId())) {
                throw new BizException("该户号已经创建客户.");
            }
        }

        String industryType = request.getIndustryType();
        if (request.getPkgId() != null && request.getPkgId() > 0) {
            ServicePkgRecord servicePkgRecord = servicePkgRecordMapper.selectById(request.getPkgId());
            if (servicePkgRecord != null) {
                request.setPkgName(servicePkgRecord.getPgkName());
            }
        }
        Consumer consumer = new Consumer();
        BeanUtils.copyProperties(request, consumer);
        consumer.setOrgCode(request.getOrgCode());


        //比较客户信息发生的变化
        //操作日志log
        OperationLogVO logVO = new OperationLogVO();
        List<Integer> logCodeList = new ArrayList<>();
        String after = JSONObject.toJSONString(request);
        String before = JSONObject.toJSONString(consumerOld);
        logVO.setOperationBefore(before);
        logVO.setOperationAfter(after);


        //比较哪些字段发生改变
        Field[] fields = consumerOld.getClass().getDeclaredFields();
        Map<String, String> compare = compareUtil.compare(fields, consumer, consumerOld);
        //修改户号
        if (StringUtil.isNotEmpty(compare.get("subsCode"))) {
            logCodeList.add(OperationTypeEnum.OPERATION_TYPE_6.getCode());
        }
        //修改客户名称
        if (StringUtil.isNotEmpty(compare.get("name"))) {
            logCodeList.add(OperationTypeEnum.OPERATION_TYPE_7.getCode());
        }
        //修改经纬度
        if (StringUtil.isNotEmpty(compare.get("positionLat")) || StringUtil.isNotEmpty(compare.get("positionLon"))) {
            logCodeList.add(OperationTypeEnum.OPERATION_TYPE_8.getCode());
        }
        dtuMapper.updateByConsumerId(request.getId(),request.getPositionLat(),request.getPositionLon(),request.getInstallationAddress());
        //修改所属行业
        if (StringUtil.isNotEmpty(compare.get("industryType"))) {
            logCodeList.add(OperationTypeEnum.OPERATION_TYPE_9.getCode());
        }
        //修改备注
        if (StringUtil.isNotEmpty(compare.get("remark"))) {
            logCodeList.add(OperationTypeEnum.OPERATION_TYPE_10.getCode());
        }
        //修改服务套餐
        if (StringUtil.isNotEmpty(compare.get("pkgName"))) {
            logCodeList.add(OperationTypeEnum.OPERATION_TYPE_42.getCode());
        }

        if (CollectionUtil.isNotEmpty(logCodeList)) {
            logVO.setCodeList(logCodeList);
            logVO.setTableName(TableConst.consumer.name());
            logVO.setTableKey(request.getId().toString());
            operationLogService.insertLog(logVO);
        }


        boolean flag = this.updateById(consumer);

        Consumer newOne = this.getById(consumer.getId());

        //更新用户地理位置信息
        FieldTemplate fieldTemplate = fieldTemplateMapper.getTypeBySpId(spId);
        if( Constants.FUNC_AREA_ALLOCAT_CUSTOM.equals(fieldTemplate.getFuncAreaAllocat()) ){
            consumerLocationService.updateConsumerLocationCustom(newOne,request.getFuncArea());
        }else{
            consumerLocationService.updateConsumerLocation(newOne);
        }


        //企业级操作日志
        LogVO vo = new LogVO();
        vo.setDetail(LogUtil.compareEntity(newOne, consumerOld, Consumer.class));
        LogRecordAspect.threadLocal.set(vo);


        if (!flag) {
            throw new BizException("更新客户信息失败.");
        }

        //行业未变化
        if (consumerOld.getIndustryType() != null &&  consumerOld.getIndustryType().equals(industryType)) {
            return "";
        }
        // 行业变化， 修改对应服务信息的行业
        if (request.getPkgId() != null && request.getPkgId() > 0) {
            QueryWrapper<ConsumerServiceInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(ConsumerServiceInfo::getConsumerId, consumer.getId());
            queryWrapper.lambda().eq(ConsumerServiceInfo::getIsDeleted, 0);
            List<ConsumerServiceInfo> serviceInfos = consumerServiceInfoService.list(queryWrapper);
            ServicePkgRecord servicePkgRecord = servicePkgRecordMapper.selectById(request.getPkgId());
            if (!CollectionUtils.isEmpty(serviceInfos)) {
                for (ConsumerServiceInfo serviceInfo : serviceInfos) {
                    if (servicePkgRecord != null && StringUtils.isNotEmpty(servicePkgRecord.getPgkCycleUnit()) && servicePkgRecord.getPgkCycle() != null) {
                        //周期单位
                        if ("年".equals(servicePkgRecord.getPgkCycleUnit())) {
                            serviceInfo.setEndDate(DateUtils.getDiffYearDate(serviceInfo.getStartDate(), servicePkgRecord.getPgkCycle()));
                        } else {
                            serviceInfo.setEndDate(DateUtils.getDiffMonData(serviceInfo.getStartDate(), servicePkgRecord.getPgkCycle()));
                        }
                    }
                    serviceInfo.setIndustryType(industryType);
                }
                consumerServiceInfoService.saveOrUpdateBatch(serviceInfos);
            }
        } else {
            LambdaUpdateWrapper<ConsumerServiceInfo> lqw = new LambdaUpdateWrapper<>();
            lqw.eq(ConsumerServiceInfo::getSpId, spId).eq(ConsumerServiceInfo::getConsumerId, request.getId())
                    .eq(ConsumerServiceInfo::getIsDeleted, IS_DELETED_FALSE)
                    .set(ConsumerServiceInfo::getIndustryType,industryType);
            consumerServiceInfoService.update(lqw);
        }
        // 行业变化， 修改对应设备的行业
        LambdaUpdateWrapper<Dtu> dtuUpdateWrapper = new LambdaUpdateWrapper<>();
        dtuUpdateWrapper.eq(Dtu::getSpId, spId).eq(Dtu::getConsumerId, request.getId())
            .eq(Dtu::getIsDeleted, IS_DELETED_FALSE)
            .set(Dtu::getSectorType,industryType);
        equipmentService.update(dtuUpdateWrapper);

        // 行业变化， 修改对应设备运行报告的行业
        LambdaUpdateWrapper<RunningReport> runningReportUpdateWrapper = new LambdaUpdateWrapper<>();
        runningReportUpdateWrapper.eq(RunningReport::getSpId, spId).eq(RunningReport::getConsumerId, request.getId())
            .eq(RunningReport::getIsDeleted, IS_DELETED_FALSE)
            .set(RunningReport::getIndustryType,industryType);
        runningReportService.update(runningReportUpdateWrapper);
        //行业变化，中断正在执行中的策略
        service.killWarningByIndustry(consumerOld.getId() + "");

        //判断新行业是否存在报警策略
        QueryWrapper<WarnStrategy> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(WarnStrategy::getStrategyObj, 1)
                .like(WarnStrategy::getStrategyObjValues, industryType)
                .eq(WarnStrategy::getIsDeleted, Constants.IS_DELETED_FALSE)
                .eq(WarnStrategy::getSpId, spId);
        WarnStrategy warnStrategy = warnStrategyService.getOne(queryWrapper);
        //如果修改后的行业存在报警策略, 判断客户是否存在单独策略
        if (warnStrategy != null) {
            log.info("新行业的报警策略 :{}", warnStrategy.toString());
            QueryWrapper<WarnStrategy> queryConsumerWrapper = new QueryWrapper<>();
            queryConsumerWrapper.lambda().eq(WarnStrategy::getStrategyObj, 2)
                    .like(WarnStrategy::getStrategyObjValues, request.getId() + ";")
                    .ne(WarnStrategy::getIsDisabled, 2)   //非失效策略
                    .eq(WarnStrategy::getIsDeleted, Constants.IS_DELETED_FALSE)
                    .eq(WarnStrategy::getSpId, spId);
            //可能存在冗余策略
            List<WarnStrategy> warnStrategyList = warnStrategyService.list(queryConsumerWrapper);
            if (CollectionUtil.isNotEmpty(warnStrategyList)) {
                log.info("查询到客户拥有策略 :{}", warnStrategyList.toString());
                //遍历,移除该策略对象
                Iterator<WarnStrategy> iterator = warnStrategyList.iterator();
                while (iterator.hasNext()) {
                    WarnStrategy strategy = iterator.next();
                    String objValues = strategy.getStrategyObjValues();
                    String[] consumerIds = objValues.split(";");
                    List<String> list = Arrays.asList(consumerIds);
                    ArrayList<String> newList = new ArrayList<>();
                    for (int i = 0; i < list.size(); i++) {
                        if (!list.get(i).equals(request.getId().toString())) {
                            newList.add(list.get(i));
                        }
                    }
                    // 当发现冗余数据被查询,移除要更新的数据
                    if (newList.size() == list.size()) {
                        iterator.remove();
                        continue;
                    }
                    //当该策略对象只剩当前 客户id时,策略失效
                    if (CollectionUtil.isEmpty(newList)) {
                        strategy.setIsDisabled(2);
                        log.info("warnStrategyId = {} 失效", strategy.getId());
                    } else {
                        String newObjValues = String.join(";", newList);
                        log.info("warnStrategyId = {}, 更新后的策略对象为:{}", strategy.getId(), newObjValues);
                        strategy.setStrategyObjValues(newObjValues);
                    }
                }
                //更新
                warnStrategyService.updateBatchById(warnStrategyList);
            }

            String newType = dictionaryname(industryType, Constants.INDUSTRY_TYPE_CODE);
            String oldType = dictionaryname(consumerOld.getIndustryType(), Constants.INDUSTRY_TYPE_CODE);
            if (CollectionUtil.isNotEmpty(warnStrategyList)) {
                log.info("被修改策略 -- warnStrategyList:{}", warnStrategyList.toString());
                return String.format("客户从“%s”修改成“%s”，对应的报警策略将会更换成“%s”所在的“%s”，原报警策略失效，请知悉。",
                        oldType, newType, newType, warnStrategy.getRuleName());
            } else {
                return String.format("客户从“%s”修改成“%s”，对应的报警策略将会更换成“%s”所在的“%s”，请知悉。",
                        oldType, newType, newType, warnStrategy.getRuleName());
            }
        } else {
            return "";
        }

    }

    @Override
    @Transactional
    public String updateSubsInfo(ConsumerUpdateSubsInfoRequest request) {
        String spId = ApplicationUtils.getWorkingSpId();
        //行业发生改变
        QueryWrapper<Consumer> queryOldWrapper = new QueryWrapper<>();
        queryOldWrapper.lambda().eq(Consumer::getId, request.getId())
                .eq(Consumer::getIsDeleted, Constants.IS_DELETED_FALSE)
                .eq(Consumer::getSpId, spId);
        Consumer consumerOld = this.getOne(queryOldWrapper);
        if (null == consumerOld) throw new BizException("未找到该客户记录");
        if (consumerOld.getStatus() == 1)  throw new BizException("工单进行中，客户信息不可修改");
        if (StringUtils.isEmpty(consumerOld.getSubsCode())) throw new BizException("该客户未关联燃气户号，不可进行燃气户信息更新");
        Consumer consumerNew = new Consumer();
        BeanUtils.copyProperties(consumerOld,consumerNew);
        LambdaUpdateWrapper<Consumer> updateWrapper = new LambdaUpdateWrapper<>();
        if (!StringUtils.isEmpty(request.getCustName())){
            consumerNew.setCustName(request.getCustName());
            updateWrapper.set(Consumer::getCustName,request.getCustName());
        }
        if (!StringUtils.isEmpty(request.getCustAddress())){
            consumerNew.setCustAddress(request.getCustAddress());
            updateWrapper.set(Consumer::getCustAddress,request.getCustAddress());
        }
        if (!StringUtils.isEmpty(request.getCustPhone())){
            consumerNew.setCustPhone(request.getCustPhone());
            updateWrapper.set(Consumer::getCustPhone,request.getCustPhone());
        }
        if (!StringUtils.isEmpty(request.getCustType())){
            consumerNew.setCustType(request.getCustType());
            updateWrapper.set(Consumer::getCustType,request.getCustType());
            updateWrapper.set(Consumer::getCustTypeCode,request.getCustTypeCode());
        }
        if (!StringUtils.isEmpty(request.getCustStatus())){
            consumerNew.setCustStatus(request.getCustStatus());
            updateWrapper.set(Consumer::getCustStatus,request.getCustStatus());
        }

        if (!StringUtils.isEmpty(request.getCustName()) || !StringUtils.isEmpty(request.getCustAddress()) ||
                !StringUtils.isEmpty(request.getCustPhone()) || !StringUtils.isEmpty(request.getCustType())
        || !StringUtils.isEmpty(request.getCustStatus())){
            updateWrapper.eq(Consumer::getId,request.getId());
            updateWrapper.eq(Consumer::getSpId,spId);
            this.update(updateWrapper);
        }else{
            throw new BizException("没有需要更新的内容");
        }

        OperationLogVO logVO = new OperationLogVO();
        List<Integer> logCodeList = new ArrayList<>();
        String after = JSONObject.toJSONString(consumerNew);
        String before = JSONObject.toJSONString(consumerOld);
        logVO.setOperationBefore(before);
        logVO.setOperationAfter(after);

        Field[] fields = consumerOld.getClass().getDeclaredFields();
        Map<String, String> compare = compareUtil.compare(fields, consumerNew, consumerOld);
        //修改户名
        if (StringUtil.isNotEmpty(compare.get("custName"))) {
            logCodeList.add(OperationTypeEnum.OPERATION_TYPE_44.getCode());
        }

        //修改户址
        if (StringUtil.isNotEmpty(compare.get("custAddress"))) {
            logCodeList.add(OperationTypeEnum.OPERATION_TYPE_45.getCode());
        }

        //修改户主手机号
        if (StringUtil.isNotEmpty(compare.get("custPhone"))) {
            logCodeList.add(OperationTypeEnum.OPERATION_TYPE_46.getCode());
        }

        //修改户号类型
        if (StringUtil.isNotEmpty(compare.get("custType"))) {
            logCodeList.add(OperationTypeEnum.OPERATION_TYPE_47.getCode());
        }

        //修改户号状态
        if (StringUtil.isNotEmpty(compare.get("custStatus"))) {
            logCodeList.add(OperationTypeEnum.OPERATION_TYPE_48.getCode());
        }

        updateContacts(consumerNew);

        if (CollectionUtil.isNotEmpty(logCodeList)) {
            logVO.setCodeList(logCodeList);
            logVO.setTableName(TableConst.consumer.name());
            logVO.setTableKey(request.getId().toString());
            operationLogService.insertLog(logVO);
        }

        //企业级操作日志
        LogVO vo = new LogVO();
        vo.setDetail(LogUtil.compareEntity(consumerNew, consumerOld, Consumer.class));
        LogRecordAspect.threadLocal.set(vo);
        return "";
    }

    /**
     * 更新客户联系人信息
     * @param consumer
     */
    @Override
    public void updateContacts(Consumer consumer){
        LambdaQueryWrapper<Contacts> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(Contacts::getSpId, consumer.getSpId());
        queryWrapper1.eq(Contacts::getConsumerId,consumer.getId());
        queryWrapper1.eq(Contacts::getIsDeleted,false);
        queryWrapper1.eq(Contacts::getTag, PhoneTypeEnum.TYPE_0.getCode());
        List<Contacts> contactsList = contactsService.getBaseMapper().selectList(queryWrapper1);
        if (CollectionUtil.isEmpty(contactsList)) {
            Contacts contacts = new Contacts();
            contacts.setConsumerId(consumer.getId());
            contacts.setName(consumer.getCustName());
            contacts.setTelephone(consumer.getCustPhone());
            contacts.setLevel(1);
            contacts.setSpId(consumer.getSpId());
            contacts.setTag(PhoneTypeEnum.TYPE_0.getCode());
            contacts.setRemark(PhoneTypeEnum.TYPE_0.getMsg());
            contactsService.getBaseMapper().insert(contacts);
        }else{
            Contacts contacts = contactsList.get(0);
            contacts.setName(consumer.getCustName());
            contacts.setTelephone(consumer.getCustPhone());
            contactsService.getBaseMapper().updateById(contacts);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void editContacts(ContactsEditRequest request) {
        log.info("编辑用户联系人入参:{}", JSONObject.toJSONString(request));

        //校验
        if (CollectionUtil.isNotEmpty(request.getContactsList())) {
            List<String> telephoneList = request.getContactsList().stream().map(ContactsRequest::getTelephone).collect(Collectors.toList());
            telephoneList.forEach(s -> {
                boolean isMatch = Pattern.matches(phoneRegex, s);
                boolean landlineMatch = Pattern.matches(landlineRegex, s);
                boolean landlineMatchs = Pattern.matches(landlineRegexs, s);
                if (!isMatch && !landlineMatch && !landlineMatchs) throw new BizException("联系方式格式存在错误");
            });
            boolean isRepeat = telephoneList.size() != new HashSet<String>(telephoneList).size();
            if (isRepeat) {
                throw new BizException("同联系人电话请勿重复填写.");
            }
            for (ContactsRequest contactsRequest : request.getContactsList()) {
                if (StringUtil.isEmpty(contactsRequest.getName()) ||
                        StringUtil.isEmpty(contactsRequest.getTelephone()) ||
                        contactsRequest.getLevel() == null) {
                    throw new BizException("联系人信息请填写完整!");
                }
            }
        }
        String spId = ApplicationUtils.getWorkingSpId();

        QueryWrapper<Contacts> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Contacts::getConsumerId, request.getId())
                .eq(Contacts::getIsDeleted, Constants.IS_DELETED_FALSE)
                .eq(Contacts::getSpId, spId);
        List<Contacts> contactsList = contactsService.list(queryWrapper);
        log.info("编辑前联系人:{}", contactsList.toString());
        //编辑后联系人id
        List<Integer> ids = request.getContactsList().stream().map(ContactsRequest::getId).collect(Collectors.toList());
        log.info("编辑后联系人:{}", ids.toString());

        for (ContactsRequest contactsRequest : request.getContactsList()) {
            if (contactsRequest.getId() == null) {
                //新增联系人
                Contacts contacts = new Contacts();
                BeanUtils.copyProperties(contactsRequest, contacts);
                contacts.setConsumerId(request.getId());
                contacts.setSpId(spId);
                contactsService.addContacts(contacts);
                continue;
            }
            for (Contacts contacts : contactsList) {
                if (contactsRequest.getId().equals(contacts.getId())) {
                    //判断联系人信息是否发生改变
                    //操作日志log-15, log-16, log-17,log-18
                    OperationLogVO logVO = new OperationLogVO();
                    List<Integer> logCodeList = new ArrayList<>();
                    if (!contactsRequest.getName().equals(contacts.getName())) {
                        logCodeList.add(OperationTypeEnum.OPERATION_TYPE_15.getCode());
                    }
                    if (!contactsRequest.getTelephone().equals(contacts.getTelephone())) {
                        logCodeList.add(OperationTypeEnum.OPERATION_TYPE_16.getCode());
                    }
                    if (!contactsRequest.getLevel().equals(contacts.getLevel())) {
                        logCodeList.add(OperationTypeEnum.OPERATION_TYPE_17.getCode());
                        logVO.setOperationBefore(contacts.getLevel().toString());
                        logVO.setOperationAfter(contactsRequest.getLevel().toString());
                    }
                    if (!contactsRequest.getRemark().equals(contacts.getRemark())) {
                        logCodeList.add(OperationTypeEnum.OPERATION_TYPE_18.getCode());
                    }
                    if (CollectionUtil.isNotEmpty(logCodeList)) {
                        logVO.setCodeList(logCodeList);
                        logVO.setTableName(TableConst.t_gss_contacts.name());
                        logVO.setTableKey(contacts.getId().toString());
                        operationLogService.insertLog(logVO);
                        //更新
                        Contacts contactsNew = new Contacts();
                        BeanUtils.copyProperties(contactsRequest, contactsNew);
                        contactsNew.setConsumerId(request.getId());
                        contactsService.updateById(contactsNew);
                        //企业级操作日志
                        contactsService.editContacts(contactsNew,contacts);
                    }

                }
            }
        }


        for (Contacts contacts : contactsList) {
            if (!ids.contains(contacts.getId())) {
                //删除联系人
                contactsService.deleteContacts(request.getId(),contacts);
            }
        }


    }


    @Override
    public List<ContactsResponse> contactsListByConsumer(ContactsEditRequest request) {
        String spId = ApplicationUtils.getWorkingSpId();

        QueryWrapper<Consumer> queryOldWrapper = new QueryWrapper<>();
        queryOldWrapper.lambda().eq(Consumer::getId, request.getId())
                .eq(Consumer::getIsDeleted, Constants.IS_DELETED_FALSE)
                .eq(Consumer::getSpId, spId);
        Consumer consumerOld = this.getOne(queryOldWrapper);
        if (consumerOld!=null&&consumerOld.getStatus()==1)  throw new BizException("工单进行中，客户信息不可修改");
        //获取联系人列表
        QueryWrapper<Contacts> contactsWrapper = new QueryWrapper<>();
        contactsWrapper.lambda().eq(Contacts::getConsumerId, request.getId())
                .eq(Contacts::getIsDeleted, Constants.IS_DELETED_FALSE)
                .in(Contacts::getSpId, spId)
                .orderByAsc(Contacts::getLevel)
                .orderByDesc(Contacts::getUpdatedAt);
        List<Contacts> contactsListNew = contactsService.list(contactsWrapper);
        List<ContactsResponse> contactsResponseList = BeanConvertUtils.convertListTo(contactsListNew, ContactsResponse::new);
        //级别名称

        for (ContactsResponse contactsResponse : contactsResponseList) {
            if (contactsResponse.getLevel() != null) {
                DictionaryItemRespDTO communicationModeDict = holder.getDictionaryByKey(
                        Constants.CONTACT_LEVEL).stream().filter(a -> a.getValue().equals(
                        contactsResponse.getLevel().toString())).collect(Collectors.toList()).get(0);
                contactsResponse.setLevelName(communicationModeDict.getName());
            }
        }

        List<ContactsResponse> contactsResponses = BeanConvertUtils.convertListTo(contactsListNew, ContactsResponse::new);
        return contactsResponses;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void bindingEquipment(ConsumerBindingRequest request) {
        String spId = ApplicationUtils.getWorkingSpId();
        if (StringUtil.isEmpty(spId)) {
            spId = request.getSpId();
        }

        //确定是哪种模板调用
        FieldTemplate template = fieldTemplateMapper.getTypeBySpId(spId);
        if (request.getBindChannel() == null) {
            request.setBindChannel(template.getTemplateType());
        }
        QueryWrapper<Consumer> consumerQueryWrapper = new QueryWrapper<>();
        consumerQueryWrapper.lambda().eq(Consumer::getId, request.getConsumerId())
                .eq(Consumer::getSpId, spId)
                .eq(Consumer::getIsDeleted, Constants.IS_DELETED_FALSE);
        Consumer consumer = consumerMapper.selectOne(consumerQueryWrapper);
        if( StringUtils.isNotEmpty(consumer.getSubsCode()) ){
            workOrderHistoryService.existWorkOrder(consumer.getSubsCode(),spId);
        }
        Consumer consumerNew = new Consumer();
        consumerNew.setEquipmentTotal(consumer.getEquipmentTotal());
        for (BindingPositionRequest positionRequest : request.getImeiList()) {
            String imei = positionRequest.getImei();
            QueryWrapper<Dtu> DtuWrapper = new QueryWrapper<>();
            DtuWrapper.lambda().eq(Dtu::getIMEI, imei)
                    .eq(Dtu::getIsDeleted, Constants.IS_DELETED_FALSE)
                    .eq(Dtu::getConsumerId, 0)
                    .eq(Dtu::getSpId, spId);
            List<Dtu> dtuList = equipmentService.list(DtuWrapper);
            if (CollectionUtil.isEmpty(dtuList)) {
                throw new BizException("该IMEI不存在或已绑定客户");
            }
            //更新dtu
            Dtu dtu = new Dtu();
            dtu.setConsumerId(request.getConsumerId());
            dtu.setSectorType(StringUtils.isBlank(consumer.getIndustryType()) ? Constants.BLANK : consumer.getIndustryType());
            dtu.setInstallDate(StringUtils.isBlank(positionRequest.getInstallDate())
                    ?DateUtil.formatDate(new Date()):positionRequest.getInstallDate());
            //根据不同渠道更新设备的安装地址;
            //时刻助手绑定设备,安装地址在同步接口中更新

            //报警器后台绑定, 此处同步客户的地址和经纬度
            if (BIND_CHANNEL_GAS == request.getBindChannel() || BIND_CHANNEL_MBP == request.getBindChannel()
                    || BIND_CHANNEL_ZJ_WIFI == request.getBindChannel()) {
                dtu.setInstallationAddress(StringUtil.isEmpty(consumer.getCustAddress())?request.getAddress():consumer.getCustAddress());
                dtu.setPositionLat(consumer.getPositionLat()==null?request.getPositionLat():consumer.getPositionLat());
                dtu.setPositionLon(consumer.getPositionLon()==null?request.getPositionLon():consumer.getPositionLon());
            }
            // 未开启安装位置校验, 入参没有安装位置
            if (checkSwitch) dtu.setInstallationPosition(positionRequest.getInstallationPosition());
            dtu.setSource(request.getSource());
            equipmentService.update(dtu, DtuWrapper);   // 更新 主体的绑定
            List<String> imeiUpdateList = dtuList.stream().map(Dtu::getIMEI).collect(Collectors.toList());
            String now = DateUtil.now();
            dtuAepMapper.bindingEquipment(imeiUpdateList, spId, now);  //更新aep表开通时间,状态

            //对于控制器类型
            if (dtuList.get(0).getEquipmentType().equals(EquipmentType.GAS_ALARM_CONTROLLER.getCode())) {
                QueryWrapper<Dtu> DtuWrapper1 = new QueryWrapper<>();
                DtuWrapper1.lambda().likeRight(Dtu::getIMEI, imei + "-")  // 将 IMEI-  XX-XX的设备同时进行绑定;
                        .eq(Dtu::getIsDeleted, Constants.IS_DELETED_FALSE)
                        .eq(Dtu::getSpId, spId);
                dtuMapper.update(dtu, DtuWrapper1);// 如果有 点型探测器, 更新绑定
            }

            //更新客户 设备数, 点位数
            //当前客户的点位数
            QueryWrapper<Dtu> dtuQueryWrapper = new QueryWrapper<>();
            dtuQueryWrapper.lambda().like(Dtu::getIMEI, "-")
                    .eq(Dtu::getConsumerId, request.getConsumerId())
                    .eq(Dtu::getIsDeleted, Constants.IS_DELETED_FALSE)
                    .eq(Dtu::getSpId, spId);
            List<Dtu> dtus = dtuMapper.selectList(dtuQueryWrapper);
            consumerNew.setEquipmentTotal(consumerNew.getEquipmentTotal() + 1);
            log.info("设备:{}绑定, 客户id={}, 设备总数={}, 原点位数={}, 现点位数={}", imei, consumer.getId(), consumerNew.getEquipmentTotal(), consumer.getPointTotal(), dtus.size());
            consumerNew.setPointTotal(dtus.size());
            //绑定记录新增
            ConsumerDtuHistory history = new ConsumerDtuHistory();
            history.setId(null);
            history.setBindChannel(request.getBindChannel());
            history.setOutOrderCode(request.getOutOrderCode());
            history.setDeviceId(dtuList.get(0).getId());
            history.setEvent(1);
            history.setIMEI(imei);
            history.setConsumerId(consumer.getId());

            if (request.getBindChannel().equals(BIND_CHANNEL_GAS)) {
                history.setOperationPersonCode(ApplicationUtils.getWorkingUser().getUsername());
                history.setOperationPersonName(ApplicationUtils.getWorkingUser().getName());
            } else if (request.getBindChannel().equals(BIND_CHANNEL_ASST)) {
                history.setOperationPersonCode("时刻助手销售单");
                history.setOperationPersonName("asst");
            } else if (request.getBindChannel().equals(BIND_CHANNEL_ZJ_WIFI)) {
                history.setOperationPersonCode("智慧厨房");
                history.setOperationPersonName("smartKitchen");
            }else {
                history.setOperationPersonCode("时刻助手销售单");
                history.setOperationPersonName("asst");
            }
            history.setRemark(Constants.STR_EMPTY);
            history.setSpId(spId);
            //当没有点型探测器被绑定时
            consumerDtuHistoryMapper.insert(history);
            //生成服务信息
            dtu.setIMEI(imei);
            dtu.setSpId(spId);
            consumerServiceInfoService.addConsumerServiceInfo(request.getIsUpdate(), imei,consumer);

            //操作日志log-19
            try {
                OperationLogVO logVO = new OperationLogVO();
                List<Integer> logCodeList = new ArrayList<>();
                logCodeList.add(OperationTypeEnum.OPERATION_TYPE_19.getCode());
                logVO.setCodeList(logCodeList);
                logVO.setTableName(TableConst.t_gss_consumer_dtu_history.name());
                logVO.setTableKey(imei);
                logVO.setOperationPersonCode(history.getOperationPersonCode());
                logVO.setOperationPersonName(history.getOperationPersonName());
                logVO.setSpId(spId);
                operationLogService.insertLog(logVO);
            } catch (Exception e) {
              log.info("bindingEquipment-error:{}",e);
            }

            //若是 余杭设备进行绑定,需要注册到政府平台
            if (spId.equals(hangzhouSpId)) {
                log.info("绑定设备:{}归属余杭,推送至杭州本地化,准备注册.", imei);
                registerCityDevice(spId, imei);
                QueryWrapper<Dtu> dtuWrapper1 = new QueryWrapper<>();
                dtuWrapper1.lambda().likeRight(Dtu::getIMEI, imei + "-")  // 将 IMEI-  XX-XX的设备同时进行注册;
                        .eq(Dtu::getConsumerId, request.getConsumerId())
                        .eq(Dtu::getIsDeleted, Constants.IS_DELETED_FALSE)
                        .eq(Dtu::getSpId, spId);
                List<Dtu> dtuList1 = dtuMapper.selectList(dtuWrapper1);

                if (CollectionUtil.isNotEmpty(dtuList1)) {
                    for (Dtu dtu1 : dtuList1) {
                        registerCityDevice(spId, dtu1.getIMEI());
                    }
                }
            }
        }
        consumerMapper.update(consumerNew, consumerQueryWrapper);
        //更新客户设备数量信息
        consumerLocationService.updateConsumerLocationDeviceNum(spId,request.getConsumerId());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void importBindingEquipment(ConsumerBindingRequest request) {
        String spId = request.getSpId();
        if (StringUtil.isEmpty(spId)) {
            spId = ApplicationUtils.getWorkingSpId();
        }

        //确定是哪种模板调用
        FieldTemplate template = fieldTemplateMapper.getTypeBySpId(spId);
        if (request.getBindChannel() == null) {
            request.setBindChannel(template.getTemplateType());
        }
        QueryWrapper<Consumer> consumerQueryWrapper = new QueryWrapper<>();
        consumerQueryWrapper.lambda().eq(Consumer::getId, request.getConsumerId())
                .eq(Consumer::getSpId, spId)
                .eq(Consumer::getIsDeleted, Constants.IS_DELETED_FALSE);
        Consumer consumer = consumerMapper.selectOne(consumerQueryWrapper);
        workOrderHistoryService.existWorkOrder(consumer.getSubsCode(),spId);
        Consumer consumerNew = new Consumer();
        consumerNew.setEquipmentTotal(consumer.getEquipmentTotal());
        for (BindingPositionRequest positionRequest : request.getImeiList()) {
            String imei = positionRequest.getImei();
            QueryWrapper<Dtu> DtuWrapper = new QueryWrapper<>();
            DtuWrapper.lambda().eq(Dtu::getIMEI, imei)
                    .eq(Dtu::getIsDeleted, Constants.IS_DELETED_FALSE)
                    .eq(Dtu::getConsumerId, 0)
                    .eq(Dtu::getSpId, spId);
            List<Dtu> dtuList = equipmentService.list(DtuWrapper);
            if (CollectionUtil.isEmpty(dtuList)) {
                throw new BizException("该IMEI不存在或已绑定客户");
            }
            //更新dtu
            Dtu dtu = new Dtu();
            dtu.setConsumerId(request.getConsumerId());
            dtu.setSectorType(StringUtils.isBlank(consumer.getIndustryType()) ? Constants.BLANK : consumer.getIndustryType());
            dtu.setInstallDate(StringUtils.isBlank(positionRequest.getInstallDate())
                    ?DateUtil.formatDate(new Date()):positionRequest.getInstallDate());
            //根据不同渠道更新设备的安装地址;
            //时刻助手绑定设备,安装地址在同步接口中更新

            //报警器后台绑定, 此处同步客户的地址和经纬度
            if (BIND_CHANNEL_GAS == request.getBindChannel() || BIND_CHANNEL_MBP == request.getBindChannel()
                    || BIND_CHANNEL_ZJ_WIFI == request.getBindChannel()) {
                dtu.setInstallationAddress(StringUtil.isEmpty(consumer.getCustAddress())?request.getAddress():consumer.getCustAddress());
                dtu.setPositionLat(consumer.getPositionLat()==null?request.getPositionLat():consumer.getPositionLat());
                dtu.setPositionLon(consumer.getPositionLon()==null?request.getPositionLon():consumer.getPositionLon());
            }
            // 未开启安装位置校验, 入参没有安装位置
            if (checkSwitch) dtu.setInstallationPosition(positionRequest.getInstallationPosition());
            dtu.setSource(request.getSource());
            equipmentService.update(dtu, DtuWrapper);   // 更新 主体的绑定
            List<String> imeiUpdateList = dtuList.stream().map(Dtu::getIMEI).collect(Collectors.toList());
            String now = DateUtil.now();
            dtuAepMapper.bindingEquipment(imeiUpdateList, spId, now);  //更新aep表开通时间,状态

            //对于控制器类型
            if (dtuList.get(0).getEquipmentType().equals(EquipmentType.GAS_ALARM_CONTROLLER.getCode())) {
                QueryWrapper<Dtu> DtuWrapper1 = new QueryWrapper<>();
                DtuWrapper1.lambda().likeRight(Dtu::getIMEI, imei + "-")  // 将 IMEI-  XX-XX的设备同时进行绑定;
                        .eq(Dtu::getIsDeleted, Constants.IS_DELETED_FALSE)
                        .eq(Dtu::getSpId, spId);
                dtuMapper.update(dtu, DtuWrapper1);// 如果有 点型探测器, 更新绑定
            }

            //更新客户 设备数, 点位数
            //当前客户的点位数
            QueryWrapper<Dtu> dtuQueryWrapper = new QueryWrapper<>();
            dtuQueryWrapper.lambda().like(Dtu::getIMEI, "-")
                    .eq(Dtu::getConsumerId, request.getConsumerId())
                    .eq(Dtu::getIsDeleted, Constants.IS_DELETED_FALSE)
                    .eq(Dtu::getSpId, spId);
            List<Dtu> dtus = dtuMapper.selectList(dtuQueryWrapper);
            consumerNew.setEquipmentTotal(consumerNew.getEquipmentTotal() + 1);
            log.info("设备:{}绑定, 客户id={}, 设备总数={}, 原点位数={}, 现点位数={}", imei, consumer.getId(), consumerNew.getEquipmentTotal(), consumer.getPointTotal(), dtus.size());
            consumerNew.setPointTotal(dtus.size());
            //绑定记录新增
            ConsumerDtuHistory history = new ConsumerDtuHistory();
            history.setId(null);
            history.setBindChannel(request.getBindChannel());
            history.setOutOrderCode(request.getOutOrderCode());
            history.setDeviceId(dtuList.get(0).getId());
            history.setEvent(1);
            history.setIMEI(imei);
            history.setConsumerId(consumer.getId());

            if (request.getBindChannel().equals(BIND_CHANNEL_GAS)) {
                history.setOperationPersonCode(ApplicationUtils.getWorkingUser().getUsername());
                history.setOperationPersonName(ApplicationUtils.getWorkingUser().getName());
            } else if (request.getBindChannel().equals(BIND_CHANNEL_ASST)) {
                history.setOperationPersonCode("时刻助手销售单");
                history.setOperationPersonName("asst");
            } else if (request.getBindChannel().equals(BIND_CHANNEL_ZJ_WIFI)) {
                history.setOperationPersonCode("智慧厨房");
                history.setOperationPersonName("smartKitchen");
            }else {
                history.setOperationPersonCode("时刻助手销售单");
                history.setOperationPersonName("asst");
            }
            history.setRemark(Constants.STR_EMPTY);
            history.setSpId(spId);
            //当没有点型探测器被绑定时
            consumerDtuHistoryMapper.insert(history);
            //生成服务信息
            dtu.setIMEI(imei);
            dtu.setSpId(spId);
            consumerServiceInfoService.addConsumerServiceInfo(request.getIsUpdate(), imei,consumer);

            //操作日志log-19
            try {
                OperationLogVO logVO = new OperationLogVO();
                List<Integer> logCodeList = new ArrayList<>();
                logCodeList.add(OperationTypeEnum.OPERATION_TYPE_19.getCode());
                logVO.setCodeList(logCodeList);
                logVO.setTableName(TableConst.t_gss_consumer_dtu_history.name());
                logVO.setTableKey(imei);
                logVO.setOperationPersonCode(history.getOperationPersonCode());
                logVO.setOperationPersonName(history.getOperationPersonName());
                logVO.setSpId(spId);
                operationLogService.insertLog(logVO);
            } catch (Exception e) {
                log.info("bindingEquipment-error:{}",e);
            }

            //若是 余杭设备进行绑定,需要注册到政府平台
            if (spId.equals(hangzhouSpId)) {
                log.info("绑定设备:{}归属余杭,推送至杭州本地化,准备注册.", imei);
                registerCityDevice(spId, imei);
                QueryWrapper<Dtu> dtuWrapper1 = new QueryWrapper<>();
                dtuWrapper1.lambda().likeRight(Dtu::getIMEI, imei + "-")  // 将 IMEI-  XX-XX的设备同时进行注册;
                        .eq(Dtu::getConsumerId, request.getConsumerId())
                        .eq(Dtu::getIsDeleted, Constants.IS_DELETED_FALSE)
                        .eq(Dtu::getSpId, spId);
                List<Dtu> dtuList1 = dtuMapper.selectList(dtuWrapper1);

                if (CollectionUtil.isNotEmpty(dtuList1)) {
                    for (Dtu dtu1 : dtuList1) {
                        registerCityDevice(spId, dtu1.getIMEI());
                    }
                }
            }
        }
        consumerMapper.update(consumerNew, consumerQueryWrapper);
        //更新客户设备数量信息
        consumerLocationService.updateConsumerLocationDeviceNum(spId,request.getConsumerId());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void importAZBindingEquipment(ConsumerBindingRequest request) {
        String spId = ApplicationUtils.getWorkingSpId();
        if (StringUtil.isEmpty(spId)) {
            spId = request.getSpId();
        }

        //确定是哪种模板调用
        FieldTemplate template = fieldTemplateMapper.getTypeBySpId(spId);
        if (request.getBindChannel() == null) {
            request.setBindChannel(template.getTemplateType());
        }
        QueryWrapper<Consumer> consumerQueryWrapper = new QueryWrapper<>();
        consumerQueryWrapper.lambda().eq(Consumer::getId, request.getConsumerId())
                .eq(Consumer::getSpId, spId)
                .eq(Consumer::getIsDeleted, Constants.IS_DELETED_FALSE);
        Consumer consumer = consumerMapper.selectOne(consumerQueryWrapper);
        workOrderHistoryService.existWorkOrder(consumer.getSubsCode(),spId);
        Consumer consumerNew = new Consumer();
        consumerNew.setEquipmentTotal(consumer.getEquipmentTotal());
        for (BindingPositionRequest positionRequest : request.getImeiList()) {
            String imei = positionRequest.getImei();
            QueryWrapper<Dtu> DtuWrapper = new QueryWrapper<>();
            DtuWrapper.lambda().eq(Dtu::getIMEI, imei)
                    .eq(Dtu::getIsDeleted, Constants.IS_DELETED_FALSE)
                    .eq(Dtu::getConsumerId, 0)
                    .eq(Dtu::getSpId, spId);
            List<Dtu> dtuList = equipmentService.list(DtuWrapper);
            if (CollectionUtil.isEmpty(dtuList)) {
                throw new BizException("该IMEI不存在或已绑定客户");
            }
            //更新dtu
            Dtu dtu = new Dtu();
            dtu.setConsumerId(request.getConsumerId());
            dtu.setSectorType(StringUtils.isBlank(consumer.getIndustryType()) ? Constants.BLANK : consumer.getIndustryType());
            dtu.setInstallDate(StringUtils.isBlank(positionRequest.getInstallDate())
                    ?DateUtil.formatDate(new Date()):positionRequest.getInstallDate());
            //根据不同渠道更新设备的安装地址;
            //时刻助手绑定设备,安装地址在同步接口中更新

            //报警器后台绑定, 此处同步客户的地址和经纬度
            if (BIND_CHANNEL_GAS == request.getBindChannel() || BIND_CHANNEL_MBP == request.getBindChannel()
                    || BIND_CHANNEL_ZJ_WIFI == request.getBindChannel()) {
                dtu.setInstallationAddress(StringUtil.isEmpty(consumer.getCustAddress())?request.getAddress():consumer.getCustAddress());
                dtu.setPositionLat(consumer.getPositionLat()==null?request.getPositionLat():consumer.getPositionLat());
                dtu.setPositionLon(consumer.getPositionLon()==null?request.getPositionLon():consumer.getPositionLon());
            }
            // 未开启安装位置校验, 入参没有安装位置
            if (checkSwitch) dtu.setInstallationPosition(positionRequest.getInstallationPosition());
            dtu.setSource(request.getSource());
            equipmentService.update(dtu, DtuWrapper);   // 更新 主体的绑定
            List<String> imeiUpdateList = dtuList.stream().map(Dtu::getIMEI).collect(Collectors.toList());
            String now = DateUtil.now();
            dtuAepMapper.bindingEquipment(imeiUpdateList, spId, now);  //更新aep表开通时间,状态

            //对于控制器类型
            if (dtuList.get(0).getEquipmentType().equals(EquipmentType.GAS_ALARM_CONTROLLER.getCode())) {
                QueryWrapper<Dtu> DtuWrapper1 = new QueryWrapper<>();
                DtuWrapper1.lambda().likeRight(Dtu::getIMEI, imei + "-")  // 将 IMEI-  XX-XX的设备同时进行绑定;
                        .eq(Dtu::getIsDeleted, Constants.IS_DELETED_FALSE)
                        .eq(Dtu::getSpId, spId);
                dtuMapper.update(dtu, DtuWrapper1);// 如果有 点型探测器, 更新绑定
            }

            //更新客户 设备数, 点位数
            //当前客户的点位数
            QueryWrapper<Dtu> dtuQueryWrapper = new QueryWrapper<>();
            dtuQueryWrapper.lambda().like(Dtu::getIMEI, "-")
                    .eq(Dtu::getConsumerId, request.getConsumerId())
                    .eq(Dtu::getIsDeleted, Constants.IS_DELETED_FALSE)
                    .eq(Dtu::getSpId, spId);
            List<Dtu> dtus = dtuMapper.selectList(dtuQueryWrapper);
            consumerNew.setEquipmentTotal(consumerNew.getEquipmentTotal() + 1);
            log.info("设备:{}绑定, 客户id={}, 设备总数={}, 原点位数={}, 现点位数={}", imei, consumer.getId(), consumerNew.getEquipmentTotal(), consumer.getPointTotal(), dtus.size());
            consumerNew.setPointTotal(dtus.size());
            //绑定记录新增
            ConsumerDtuHistory history = new ConsumerDtuHistory();
            history.setId(null);
            history.setBindChannel(request.getBindChannel());
            history.setOutOrderCode(request.getOutOrderCode());
            history.setDeviceId(dtuList.get(0).getId());
            history.setEvent(1);
            history.setIMEI(imei);
            history.setConsumerId(consumer.getId());

            if (request.getBindChannel().equals(BIND_CHANNEL_GAS)) {
                history.setOperationPersonCode(ApplicationUtils.getWorkingUser().getUsername());
                history.setOperationPersonName(ApplicationUtils.getWorkingUser().getName());
            } else if (request.getBindChannel().equals(BIND_CHANNEL_ASST)) {
                history.setOperationPersonCode("时刻助手销售单");
                history.setOperationPersonName("asst");
            } else if (request.getBindChannel().equals(BIND_CHANNEL_ZJ_WIFI)) {
                history.setOperationPersonCode("智慧厨房");
                history.setOperationPersonName("smartKitchen");
            }else {
                history.setOperationPersonCode("时刻助手销售单");
                history.setOperationPersonName("asst");
            }
            history.setRemark(Constants.STR_EMPTY);
            history.setSpId(spId);
            //当没有点型探测器被绑定时
            consumerDtuHistoryMapper.insert(history);
            //生成服务信息
            dtu.setIMEI(imei);
            dtu.setSpId(spId);
            consumerServiceInfoService.addConsumerServiceInfo(request.getIsUpdate(), imei,consumer);

            //操作日志log-19
            try {
                OperationLogVO logVO = new OperationLogVO();
                List<Integer> logCodeList = new ArrayList<>();
                logCodeList.add(OperationTypeEnum.OPERATION_TYPE_19.getCode());
                logVO.setCodeList(logCodeList);
                logVO.setTableName(TableConst.t_gss_consumer_dtu_history.name());
                logVO.setTableKey(imei);
                logVO.setOperationPersonCode(history.getOperationPersonCode());
                logVO.setOperationPersonName(history.getOperationPersonName());
                logVO.setSpId(spId);
                operationLogService.insertLog(logVO);
            } catch (Exception e) {
                log.info("bindingEquipment-error:{}",e);
            }

            //若是 余杭设备进行绑定,需要注册到政府平台
            if (spId.equals(hangzhouSpId)) {
                log.info("绑定设备:{}归属余杭,推送至杭州本地化,准备注册.", imei);
                registerCityDevice(spId, imei);
                QueryWrapper<Dtu> dtuWrapper1 = new QueryWrapper<>();
                dtuWrapper1.lambda().likeRight(Dtu::getIMEI, imei + "-")  // 将 IMEI-  XX-XX的设备同时进行注册;
                        .eq(Dtu::getConsumerId, request.getConsumerId())
                        .eq(Dtu::getIsDeleted, Constants.IS_DELETED_FALSE)
                        .eq(Dtu::getSpId, spId);
                List<Dtu> dtuList1 = dtuMapper.selectList(dtuWrapper1);

                if (CollectionUtil.isNotEmpty(dtuList1)) {
                    for (Dtu dtu1 : dtuList1) {
                        registerCityDevice(spId, dtu1.getIMEI());
                    }
                }
            }
        }
        consumerMapper.update(consumerNew, consumerQueryWrapper);
        //更新客户设备数量信息
        consumerLocationService.updateConsumerLocationDeviceNum(spId,request.getConsumerId());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void bindingOrderEquipment(ConsumerBindingRequest request) {
        String spId = ApplicationUtils.getWorkingSpId();
        if (StringUtil.isNotEmpty(request.getSpId())) {
            spId = request.getSpId();
        }

        //确定是哪种模板调用
        FieldTemplate template = fieldTemplateMapper.getTypeBySpId(spId);
        if (request.getBindChannel() == null) {
            request.setBindChannel(template.getTemplateType());
        }
        QueryWrapper<Consumer> consumerQueryWrapper = new QueryWrapper<>();
        consumerQueryWrapper.lambda().eq(Consumer::getId, request.getConsumerId())
                .eq(Consumer::getSpId, spId)
                .eq(Consumer::getIsDeleted, Constants.IS_DELETED_FALSE);
        Consumer consumer = consumerMapper.selectOne(consumerQueryWrapper);
        //workOrderHistoryService.existWorkOrder(consumer.getSubsCode(),spId);
        Consumer consumerNew = new Consumer();
        consumerNew.setEquipmentTotal(consumer.getEquipmentTotal());
        for (BindingPositionRequest positionRequest : request.getImeiList()) {
            String imei = positionRequest.getImei();
            QueryWrapper<Dtu> DtuWrapper = new QueryWrapper<>();
            DtuWrapper.lambda().eq(Dtu::getIMEI, imei)
                    .eq(Dtu::getIsDeleted, Constants.IS_DELETED_FALSE)
                    //.eq(Dtu::getConsumerId, 0)
                    .eq(Dtu::getSpId, spId);
            List<Dtu> dtuList = equipmentService.list(DtuWrapper);
            if (CollectionUtil.isEmpty(dtuList)) {
                throw new BizException("该IMEI不存在或已绑定客户");
            }
            //更新dtu
            Dtu dtu = new Dtu();
            dtu.setConsumerId(request.getConsumerId());
            dtu.setSectorType(StringUtils.isBlank(consumer.getIndustryType()) ? Constants.BLANK : consumer.getIndustryType());
            dtu.setInstallDate(StringUtils.isBlank(positionRequest.getInstallDate())
                    ?DateUtil.formatDate(new Date()):positionRequest.getInstallDate());
            //根据不同渠道更新设备的安装地址;
            //时刻助手绑定设备,安装地址在同步接口中更新

            //报警器后台绑定, 此处同步客户的地址和经纬度
            dtu.setInstallationAddress(StringUtil.isEmpty(consumer.getCustAddress())?request.getAddress():consumer.getCustAddress());
            dtu.setPositionLat(consumer.getPositionLat()==null?request.getPositionLat():consumer.getPositionLat());
            dtu.setPositionLon(consumer.getPositionLon()==null?request.getPositionLon():consumer.getPositionLon());
            // 未开启安装位置校验, 入参没有安装位置
            if (checkSwitch) dtu.setInstallationPosition(positionRequest.getInstallationPosition());
            dtu.setSource(request.getSource());
            equipmentService.update(dtu, DtuWrapper);   // 更新 主体的绑定
            List<String> imeiUpdateList = dtuList.stream().map(Dtu::getIMEI).collect(Collectors.toList());
            String now = DateUtil.now();
            dtuAepMapper.bindingEquipment(imeiUpdateList, spId, now);  //更新aep表开通时间,状态

            //对于控制器类型
            if (dtuList.get(0).getEquipmentType().equals(EquipmentType.GAS_ALARM_CONTROLLER.getCode())) {
                QueryWrapper<Dtu> DtuWrapper1 = new QueryWrapper<>();
                DtuWrapper1.lambda().likeRight(Dtu::getIMEI, imei + "-")  // 将 IMEI-  XX-XX的设备同时进行绑定;
                        .eq(Dtu::getIsDeleted, Constants.IS_DELETED_FALSE)
                        .eq(Dtu::getSpId, spId);
                dtuMapper.update(dtu, DtuWrapper1);// 如果有 点型探测器, 更新绑定
            }

            //更新客户 设备数, 点位数
            //当前客户的点位数
            QueryWrapper<Dtu> dtuQueryWrapper = new QueryWrapper<>();
            dtuQueryWrapper.lambda().like(Dtu::getIMEI, "-")
                    .eq(Dtu::getConsumerId, request.getConsumerId())
                    .eq(Dtu::getIsDeleted, Constants.IS_DELETED_FALSE)
                    .eq(Dtu::getSpId, spId);
            List<Dtu> dtus = dtuMapper.selectList(dtuQueryWrapper);
            consumerNew.setEquipmentTotal(consumerNew.getEquipmentTotal() + 1);
            log.info("设备:{}绑定, 客户id={}, 设备总数={}, 原点位数={}, 现点位数={}", imei, consumer.getId(), consumerNew.getEquipmentTotal(), consumer.getPointTotal(), dtus.size());
            consumerNew.setPointTotal(dtus.size());
            //绑定记录新增
            ConsumerDtuHistory history = new ConsumerDtuHistory();
            history.setId(null);
            history.setBindChannel(request.getBindChannel());
            history.setOutOrderCode(request.getOutOrderCode());
            history.setDeviceId(dtuList.get(0).getId());
            history.setEvent(1);
            history.setIMEI(imei);
            history.setConsumerId(consumer.getId());

            if (request.getBindChannel().equals(BIND_CHANNEL_GAS)) {
                history.setOperationPersonCode(ApplicationUtils.getWorkingUser().getUsername());
                history.setOperationPersonName(ApplicationUtils.getWorkingUser().getName());
            } else if (request.getBindChannel().equals(BIND_CHANNEL_ASST)) {
                history.setOperationPersonCode("时刻助手销售单");
                history.setOperationPersonName("asst");
            } else if (request.getBindChannel().equals(BIND_CHANNEL_ZJ_WIFI)) {
                history.setOperationPersonCode("智慧厨房");
                history.setOperationPersonName("smartKitchen");
            }else {
                history.setOperationPersonCode("时刻助手销售单");
                history.setOperationPersonName("asst");
            }
            history.setRemark(Constants.STR_EMPTY);
            history.setSpId(spId);
            //当没有点型探测器被绑定时
            consumerDtuHistoryMapper.insert(history);
            //生成服务信息
            dtu.setIMEI(imei);
            dtu.setSpId(spId);
            consumerServiceInfoService.addConsumerServiceInfo(request.getIsUpdate(), imei,consumer);

            //操作日志log-19
            try {
                OperationLogVO logVO = new OperationLogVO();
                List<Integer> logCodeList = new ArrayList<>();
                logCodeList.add(OperationTypeEnum.OPERATION_TYPE_19.getCode());
                logVO.setCodeList(logCodeList);
                logVO.setTableName(TableConst.t_gss_consumer_dtu_history.name());
                logVO.setTableKey(imei);
                logVO.setOperationPersonCode(history.getOperationPersonCode());
                logVO.setOperationPersonName(history.getOperationPersonName());
                logVO.setSpId(spId);
                operationLogService.insertLog(logVO);
            } catch (Exception e) {
                log.info("bindingEquipment-error:{}",e);
            }

            //若是 余杭设备进行绑定,需要注册到政府平台
            if (spId.equals(hangzhouSpId)) {
                log.info("绑定设备:{}归属余杭,推送至杭州本地化,准备注册.", imei);
                registerCityDevice(spId, imei);
                QueryWrapper<Dtu> dtuWrapper1 = new QueryWrapper<>();
                dtuWrapper1.lambda().likeRight(Dtu::getIMEI, imei + "-")  // 将 IMEI-  XX-XX的设备同时进行注册;
                        .eq(Dtu::getConsumerId, request.getConsumerId())
                        .eq(Dtu::getIsDeleted, Constants.IS_DELETED_FALSE)
                        .eq(Dtu::getSpId, spId);
                List<Dtu> dtuList1 = dtuMapper.selectList(dtuWrapper1);

                if (CollectionUtil.isNotEmpty(dtuList1)) {
                    for (Dtu dtu1 : dtuList1) {
                        registerCityDevice(spId, dtu1.getIMEI());
                    }
                }
            }
        }
        consumerMapper.update(consumerNew, consumerQueryWrapper);
        //更新客户设备数量信息
        consumerLocationService.updateConsumerLocationDeviceNum(spId,request.getConsumerId());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void bindingEquipmentZJ(ConsumerBindingRequest request) {
        String spId = ApplicationUtils.getWorkingSpId();
        if (StringUtil.isEmpty(spId)) {
            spId = request.getSpId();
        }

        //确定是哪种模板调用
        FieldTemplate template = fieldTemplateMapper.getTypeBySpId(spId);
        if (request.getBindChannel() == null) {
            request.setBindChannel(template.getTemplateType());
        }
        QueryWrapper<Consumer> consumerQueryWrapper = new QueryWrapper<>();
        consumerQueryWrapper.lambda().eq(Consumer::getId, request.getConsumerId())
                .eq(Consumer::getSpId, spId)
                .eq(Consumer::getIsDeleted, Constants.IS_DELETED_FALSE);
        Consumer consumer = consumerMapper.selectOne(consumerQueryWrapper);
        workOrderHistoryService.existWorkOrder(consumer.getSubsCode(),spId);
        Consumer consumerNew = new Consumer();
        consumerNew.setEquipmentTotal(consumer.getEquipmentTotal());
        for (BindingPositionRequest positionRequest : request.getImeiList()) {
            String imei = positionRequest.getImei();
            //当以前该设备在当前客户下绑定过不需要新加设备数量
            QueryWrapper<Dtu> DtuConWrapper = new QueryWrapper<>();
            DtuConWrapper.lambda().eq(Dtu::getIMEI, imei)
                    .eq(Dtu::getIsDeleted, Constants.IS_DELETED_FALSE)
                    .eq(Dtu::getConsumerId, request.getConsumerId())
                    .eq(Dtu::getSpId, spId);
            List<Dtu> dtuConList = equipmentService.list(DtuConWrapper);
            if (CollectionUtils.isEmpty(dtuConList)) {
                consumerNew.setEquipmentTotal(consumerNew.getEquipmentTotal() + 1);

                //绑定记录新增
                ConsumerDtuHistory history = new ConsumerDtuHistory();
                history.setId(null);
                history.setBindChannel(request.getBindChannel());
                history.setOutOrderCode(request.getOutOrderCode());
                history.setDeviceId(imei);
                history.setEvent(1);
                history.setIMEI(imei);
                history.setConsumerId(consumer.getId());

                if (request.getBindChannel().equals(BIND_CHANNEL_GAS)) {
                    history.setOperationPersonCode(ApplicationUtils.getWorkingUser().getUsername());
                    history.setOperationPersonName(ApplicationUtils.getWorkingUser().getName());
                } else if (request.getBindChannel().equals(BIND_CHANNEL_ASST)) {
                    history.setOperationPersonCode("时刻助手销售单");
                    history.setOperationPersonName("asst");
                } else if (request.getBindChannel().equals(BIND_CHANNEL_ZJ_WIFI)) {
                    history.setOperationPersonCode("智慧厨房");
                    history.setOperationPersonName("smartKitchen");
                }else {
                    history.setOperationPersonCode("时刻助手销售单");
                    history.setOperationPersonName("asst");
                }
                history.setRemark(Constants.STR_EMPTY);
                history.setSpId(spId);
                //当没有点型探测器被绑定时
                consumerDtuHistoryMapper.insert(history);

                //操作日志log-19
                try {
                    OperationLogVO logVO = new OperationLogVO();
                    List<Integer> logCodeList = new ArrayList<>();
                    logCodeList.add(OperationTypeEnum.OPERATION_TYPE_19.getCode());
                    logVO.setCodeList(logCodeList);
                    logVO.setTableName(TableConst.t_gss_consumer_dtu_history.name());
                    logVO.setTableKey(imei);
                    logVO.setOperationPersonCode(history.getOperationPersonCode());
                    logVO.setOperationPersonName(history.getOperationPersonName());
                    logVO.setSpId(spId);
                    operationLogService.insertLog(logVO);
                } catch (Exception e) {
                    log.info("bindingEquipment-error:{}",e);
                }
            }
            QueryWrapper<Dtu> DtuWrapper = new QueryWrapper<>();
            DtuWrapper.lambda().eq(Dtu::getIMEI, imei)
                    .eq(Dtu::getIsDeleted, Constants.IS_DELETED_FALSE)
                    .eq(Dtu::getConsumerId, 0)
                    .eq(Dtu::getSpId, spId);
            List<Dtu> dtuList = equipmentService.list(DtuWrapper);
            //更新dtu
            Dtu dtu = new Dtu();
            dtu.setConsumerId(request.getConsumerId());
            dtu.setSectorType(StringUtils.isBlank(consumer.getIndustryType()) ? Constants.BLANK : consumer.getIndustryType());
            dtu.setInstallDate(StringUtils.isBlank(positionRequest.getInstallDate())
                    ?DateUtil.formatDate(new Date()):positionRequest.getInstallDate());
            //根据不同渠道更新设备的安装地址;
            //时刻助手绑定设备,安装地址在同步接口中更新

            //报警器后台绑定, 此处同步客户的地址和经纬度
            if (BIND_CHANNEL_GAS == request.getBindChannel() || BIND_CHANNEL_MBP == request.getBindChannel()
                    || BIND_CHANNEL_ZJ_WIFI == request.getBindChannel()) {
                dtu.setInstallationAddress(StringUtil.isEmpty(consumer.getCustAddress())?request.getAddress():consumer.getCustAddress());
                dtu.setPositionLat(consumer.getPositionLat()==null?request.getPositionLat():consumer.getPositionLat());
                dtu.setPositionLon(consumer.getPositionLon()==null?request.getPositionLon():consumer.getPositionLon());
            }
            // 未开启安装位置校验, 入参没有安装位置
            if (checkSwitch) dtu.setInstallationPosition(positionRequest.getInstallationPosition());
            dtu.setSource(request.getSource());
            equipmentService.update(dtu, DtuWrapper);   // 更新 主体的绑定

            if (CollectionUtil.isNotEmpty(dtuList)) {

                List<String> imeiUpdateList = dtuList.stream().map(Dtu::getIMEI).collect(Collectors.toList());
                String now = DateUtil.now();
                dtuAepMapper.bindingEquipment(imeiUpdateList, spId, now);  //更新aep表开通时间,状态

                //对于控制器类型
                if (dtuList.get(0).getEquipmentType().equals(EquipmentType.GAS_ALARM_CONTROLLER.getCode())) {
                    QueryWrapper<Dtu> DtuWrapper1 = new QueryWrapper<>();
                    DtuWrapper1.lambda().likeRight(Dtu::getIMEI, imei + "-")  // 将 IMEI-  XX-XX的设备同时进行绑定;
                            .eq(Dtu::getIsDeleted, Constants.IS_DELETED_FALSE)
                            .eq(Dtu::getSpId, spId);
                    dtuMapper.update(dtu, DtuWrapper1);// 如果有 点型探测器, 更新绑定
                }
            }

            //更新客户 设备数, 点位数
            //当前客户的点位数
            QueryWrapper<Dtu> dtuQueryWrapper = new QueryWrapper<>();
            dtuQueryWrapper.lambda().like(Dtu::getIMEI, "-")
                    .eq(Dtu::getConsumerId, request.getConsumerId())
                    .eq(Dtu::getIsDeleted, Constants.IS_DELETED_FALSE)
                    .eq(Dtu::getSpId, spId);
            List<Dtu> dtus = dtuMapper.selectList(dtuQueryWrapper);
            log.info("设备:{}绑定, 客户id={}, 设备总数={}, 原点位数={}, 现点位数={}", imei, consumer.getId(), consumerNew.getEquipmentTotal(), consumer.getPointTotal(), dtus.size());
            consumerNew.setPointTotal(dtus.size());

            //生成服务信息
            dtu.setIMEI(imei);
            dtu.setSpId(spId);
            consumerServiceInfoService.addDeleteConsumerServiceInfo(request.getIsUpdate(), imei,consumer.getIndustryType());

            //若是 余杭设备进行绑定,需要注册到政府平台
            if (spId.equals(hangzhouSpId)) {
                log.info("绑定设备:{}归属余杭,推送至杭州本地化,准备注册.", imei);
                registerCityDevice(spId, imei);
                QueryWrapper<Dtu> dtuWrapper1 = new QueryWrapper<>();
                dtuWrapper1.lambda().likeRight(Dtu::getIMEI, imei + "-")  // 将 IMEI-  XX-XX的设备同时进行注册;
                        .eq(Dtu::getConsumerId, request.getConsumerId())
                        .eq(Dtu::getIsDeleted, Constants.IS_DELETED_FALSE)
                        .eq(Dtu::getSpId, spId);
                List<Dtu> dtuList1 = dtuMapper.selectList(dtuWrapper1);

                if (CollectionUtil.isNotEmpty(dtuList1)) {
                    for (Dtu dtu1 : dtuList1) {
                        registerCityDevice(spId, dtu1.getIMEI());
                    }
                }
            }
        }
        consumerMapper.update(consumerNew, consumerQueryWrapper);
        //更新客户设备数量信息
        consumerLocationService.updateConsumerLocationDeviceNum(spId,request.getConsumerId());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void unbindEquipment(ConsumerunBindingRequest request) {
        String spId = ApplicationUtils.getWorkingSpId();
        if (StringUtils.isEmpty(spId)) {
            spId = request.getSpId();
        }
        //判断该imei设备是否存在且绑定该客户
        LambdaQueryWrapper<Dtu> dtuQueryWrapper = new LambdaQueryWrapper<>();
        dtuQueryWrapper.eq(Dtu::getIMEI, request.getImei())

                .eq(Dtu::getIsDeleted, Constants.IS_DELETED_FALSE);

        // 兼容APP端删除设备
        if (BIND_CHANNEL_ZJ_WIFI != request.getBindChannel()) {
            dtuQueryWrapper.eq(Dtu::getConsumerId, request.getConsumerId())
                    .eq(Dtu::getSpId, spId);
        }
        log.info("unbindEquipment dtuQueryWrapper: {}", dtuQueryWrapper.getTargetSql());
        Dtu one = equipmentService.getOne(dtuQueryWrapper);
        if (one == null) {
            log.error("unbindEquipment Dtu is empty request: {}", request);
            throw new BizException("该设备不存在或未绑定该客户.");
        }

        if (BIND_CHANNEL_ZJ_WIFI == request.getBindChannel()) {
            Consumer zjConsumer = baseMapper.selectById(one.getConsumerId());
            if (zjConsumer == null || zjConsumer.getMemberId().equals(request.getConsumerId())) {
                log.error("unbindEquipment zjConsumer is empty request: {}", request);
                throw new BizException("该设备不存在或未绑定该客户.");
            }
        }

        //解绑主设备, 将 客户id, 设备名,安装位置(经纬度)全部置空
        UpdateWrapper<Dtu> updateWrapper = new UpdateWrapper<>();
        Dtu dtu = new Dtu();
        dtu.setIMEI(request.getImei());
        dtu.setConsumerId(request.getConsumerId());
        dtu.setIsDeleted(Constants.IS_DELETED_FALSE);
        dtu.setSpId(spId);
        updateWrapper.setEntity(dtu);
        updateWrapper.lambda().set(Dtu::getConsumerId, 0)
                .set(Dtu::getSectorType, Constants.BLANK)
                .set(Dtu::getName, Constants.STR_EMPTY)
                .set(Dtu::getInstallationPosition, Constants.STR_EMPTY)
                .set(Dtu::getInstallationAddress, Constants.STR_EMPTY)
                .set(Dtu::getPositionLat, null)
                .set(Dtu::getPositionLon, null);
        equipmentService.update(updateWrapper);
        //更新aep
        dtuAepMapper.unbindEquipment(request.getImei(), spId);
        //新增设备解绑记录
        ConsumerDtuHistory history = new ConsumerDtuHistory();
        history.setId(null);
        history.setOutOrderCode(request.getOutOrderCode());
        history.setBindChannel(request.getTemplateType());
        history.setDeviceId(request.getImei());
        history.setEvent(0);
        history.setIMEI(request.getImei());
        history.setConsumerId(request.getConsumerId());
        if (request.getBindChannel().equals(BIND_CHANNEL_GAS)) {
            history.setOperationPersonCode(ApplicationUtils.getWorkingUser().getUsername());
            history.setOperationPersonName(ApplicationUtils.getWorkingUser().getName());
        } else if (request.getBindChannel().equals(BIND_CHANNEL_ASST)) {
            history.setOperationPersonCode("时刻助手销售单");
            history.setOperationPersonName("asst");
        } else if (request.getBindChannel().equals(BIND_CHANNEL_ZJ_WIFI)) {
            history.setOperationPersonCode("智慧厨房");
            history.setOperationPersonName("smartKitchen");
        } else if (request.getBindChannel().equals(BIND_CHANNEL_TCIS_REFUND)) {
            history.setOperationPersonCode("时刻助手销售单");
            history.setOperationPersonName("tcis");
        } else {
            history.setOperationPersonCode("时刻助手销售单");
            history.setOperationPersonName("asst");
        }
        if( null!=request.getOperateType() && 3 == request.getOperateType() ){
            history.setBindChannel(request.getBindChannel());
            history.setRemark("退货设备解绑");
        }else{
            history.setRemark(Constants.STR_EMPTY);
        }
        history.setSpId(spId);
        consumerDtuHistoryService.save(history);
        //删除服务信息
        consumerServiceInfoService.deleteConsumerServiceInfo(request.getImei());

        //如果有点型探测器,进行解绑
        Dtu dtuPoint = new Dtu();
        int update = 0;
        dtuPoint.setName(Constants.STR_EMPTY);
        dtuPoint.setConsumerId(0);
        dtuPoint.setInstallationPosition(Constants.STR_EMPTY);
        dtuPoint.setInstallationAddress(Constants.STR_EMPTY);
        dtuPoint.setPositionLat(0d);
        dtuPoint.setPositionLon(0d);
        QueryWrapper<Dtu> queryPointWrapper = new QueryWrapper<>();
        queryPointWrapper.lambda().likeRight(Dtu::getIMEI, request.getImei() + "-")
                .eq(Dtu::getConsumerId, request.getConsumerId())
                .eq(Dtu::getSpId, spId)
                .eq(Dtu::getIsDeleted, Constants.IS_DELETED_FALSE);
        update = dtuMapper.selectList(queryPointWrapper).size();
        dtuMapper.update(dtuPoint, queryPointWrapper);
        //更新aep表
        DtuAep aep = new DtuAep();
        aep.setOpenTime("");
        aep.setOpenStatus(0);
        QueryWrapper<DtuAep> queryAepWrapper = new QueryWrapper<>();
        queryAepWrapper.lambda().likeRight(DtuAep::getIMEI, request.getImei() + "-")
                .eq(DtuAep::getSpId, spId)
                .eq(DtuAep::getIsDeleted, Constants.IS_DELETED_FALSE);
        dtuAepMapper.update(aep, queryAepWrapper);

        //更新 客户表设备数,点位数
        QueryWrapper<Consumer> queryConsumerWrapper = new QueryWrapper<>();
        queryConsumerWrapper.lambda().eq(Consumer::getId, request.getConsumerId())
                .eq(Consumer::getIsDeleted, Constants.IS_DELETED_FALSE)
                .eq(Consumer::getSpId, spId);
        Consumer consumerOld = this.getOne(queryConsumerWrapper);
        Consumer consumer = new Consumer();
        consumer.setEquipmentTotal(consumerOld.getEquipmentTotal() - 1);
        log.info("设备:{}解绑, 客户id={}, 原点位数={}, 减少点位数={}", request.getImei(), consumerOld.getId(), consumerOld.getPointTotal(), update);
        int pointTotal = consumerOld.getPointTotal() - update;
        if (pointTotal < 0) {
            log.info("客户的点位总数异常为{}", pointTotal);
            pointTotal = 0;
        }
        consumer.setPointTotal(pointTotal);
        this.update(consumer, queryConsumerWrapper);
        //更新客户设备数量信息
        consumerLocationService.updateConsumerLocationDeviceNum(spId,request.getConsumerId());

        //如果渠道二的客户或者智慧厨房紫荆报警器，解绑后没有任何设备, 删除客户
        if ((request.getTemplateType() == BIND_CHANNEL_ASST || Constants.ZJ_EQUIPMENT_FROM.equals(one.getEquipmentFrom())) && consumer.getEquipmentTotal() == 0) {
            log.info("销售单客户:{}当前已无绑定设备,进行逻辑删除", request.getConsumerId());
            Consumer consumerNew = new Consumer();
            consumerNew.setId(request.getConsumerId());
            consumerNew.setIsDeleted(true);
            this.updateById(consumerNew);
            //同步逻辑删除t_consumer_location表记录
            consumerLocationService.deleteConsumerLocation(spId,request.getConsumerId());
        }
        //同步解绑设备信息到tcis3.0
        this.syncUnbindEquipmentToTcis(request, consumerOld, spId);
        try {
            //操作日志log-20
            OperationLogVO logVO = new OperationLogVO();
            List<Integer> logCodeList = new ArrayList<>();
            logCodeList.add(OperationTypeEnum.OPERATION_TYPE_20.getCode());
            logVO.setCodeList(logCodeList);
            logVO.setTableName(TableConst.dtu.name());
            logVO.setTableKey(request.getImei());
            logVO.setSpId(spId);
            logVO.setOperationPersonCode(history.getOperationPersonCode());
            logVO.setOperationPersonName(history.getOperationPersonName());
            operationLogService.insertLog(logVO);
        } catch (Exception e) {
            log.info("unbindEquipment-error:{}",e);
        }
        HomeDeviceBindNoticeRequest requests = new HomeDeviceBindNoticeRequest();
        requests.setDeviceId(one.getDeviceCode());
        requests.setImei(request.getImei());
        if (Constants.ZJ_EQUIPMENT_FROM.equals(one.getEquipmentFrom())) {
            requests.setEquType(16);
        }else {
            requests.setEquType(19);
        }
        log.info("通知智慧厨房解绑 requests：" + requests.toString());
        String homeDeviceDelete = consoleSkFeignClient.homeDeviceUnBindNotice(requests);
        log.info("通知智慧厨房解绑 homeDeviceDelete：" + homeDeviceDelete);

        if (Constants.ZJ_EQUIPMENT_FROM.equals(one.getEquipmentFrom())) {
            //删除设备
            equipmentService.removeZJWifiDevice(request.getImei(), spId);
        }
        QueryWrapper<Dtu> queryDelWrapper = new QueryWrapper<>();
        queryDelWrapper.lambda().eq(Dtu::getParentImei, request.getImei())
                .eq(Dtu::getSpId, spId);
        List<Dtu> delList = dtuMapper.selectList(queryDelWrapper);
        for (Dtu dtu1 : delList) {
            log.info("删除报警小铃铛:" + dtu1.getIMEI());
            redisCacheExt.hashDel("alert_small_bell:" + spId, dtu1.getIMEI());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String unbindEquipmentOrder(ConsumerunBindingRequest request) {
        String spId = ApplicationUtils.getWorkingSpId();
        if (StringUtils.isNotEmpty(request.getSpId())) {
            spId = request.getSpId();
        }
        //判断该imei设备是否存在且绑定该客户
        LambdaQueryWrapper<Dtu> dtuQueryWrapper = new LambdaQueryWrapper<>();
        dtuQueryWrapper.eq(Dtu::getIMEI, request.getImei())

                .eq(Dtu::getIsDeleted, Constants.IS_DELETED_FALSE);

        // 兼容APP端删除设备
        if (BIND_CHANNEL_ZJ_WIFI != request.getBindChannel()) {
            dtuQueryWrapper.eq(Dtu::getConsumerId, request.getConsumerId())
                    .eq(Dtu::getSpId, spId);
        }
        log.info("unbindEquipment dtuQueryWrapper: {}", dtuQueryWrapper.getTargetSql());
        Dtu one = equipmentService.getOne(dtuQueryWrapper);
        if (one == null) {
            log.error("unbindEquipment Dtu is empty request: {}", request);
            return "已解绑";
        }

        if (BIND_CHANNEL_ZJ_WIFI == request.getBindChannel()) {
            Consumer zjConsumer = baseMapper.selectById(one.getConsumerId());
            if (zjConsumer == null || zjConsumer.getMemberId().equals(request.getConsumerId())) {
                log.error("unbindEquipment zjConsumer is empty request: {}", request);
                throw new BizException("该设备不存在或未绑定该客户.");
            }
        }

        //解绑主设备, 将 客户id, 设备名,安装位置(经纬度)全部置空
        UpdateWrapper<Dtu> updateWrapper = new UpdateWrapper<>();
        Dtu dtu = new Dtu();
        dtu.setIMEI(request.getImei());
        dtu.setConsumerId(request.getConsumerId());
        dtu.setIsDeleted(Constants.IS_DELETED_FALSE);
        dtu.setSpId(spId);
        updateWrapper.setEntity(dtu);
        updateWrapper.lambda().set(Dtu::getConsumerId, 0)
                .set(Dtu::getSectorType, Constants.BLANK)
                .set(Dtu::getName, Constants.STR_EMPTY)
                .set(Dtu::getInstallationPosition, Constants.STR_EMPTY)
                .set(Dtu::getInstallationAddress, Constants.STR_EMPTY)
                .set(Dtu::getPositionLat, null)
                .set(Dtu::getPositionLon, null);
        equipmentService.update(updateWrapper);
        //更新aep
        dtuAepMapper.unbindEquipment(request.getImei(), spId);
        //新增设备解绑记录
        ConsumerDtuHistory history = new ConsumerDtuHistory();
        history.setId(null);
        history.setOutOrderCode(request.getOutOrderCode());
        history.setBindChannel(request.getTemplateType());
        history.setDeviceId(request.getImei());
        history.setEvent(0);
        history.setIMEI(request.getImei());
        history.setConsumerId(request.getConsumerId());
        if (request.getBindChannel().equals(BIND_CHANNEL_GAS)) {
            history.setOperationPersonCode(ApplicationUtils.getWorkingUser().getUsername());
            history.setOperationPersonName(ApplicationUtils.getWorkingUser().getName());
        } else if (request.getBindChannel().equals(BIND_CHANNEL_ASST)) {
            history.setOperationPersonCode("时刻助手销售单");
            history.setOperationPersonName("asst");
        } else if (request.getBindChannel().equals(BIND_CHANNEL_ZJ_WIFI)) {
            history.setOperationPersonCode("智慧厨房");
            history.setOperationPersonName("smartKitchen");
        }else {
            history.setOperationPersonCode("时刻助手销售单");
            history.setOperationPersonName("asst");
        }
        history.setRemark(Constants.STR_EMPTY);
        history.setSpId(spId);
        consumerDtuHistoryService.save(history);
        //删除服务信息
        consumerServiceInfoService.deleteConsumerServiceInfo(request.getImei());

        //如果有点型探测器,进行解绑
        Dtu dtuPoint = new Dtu();
        int update = 0;
        dtuPoint.setName(Constants.STR_EMPTY);
        dtuPoint.setConsumerId(0);
        dtuPoint.setInstallationPosition(Constants.STR_EMPTY);
        dtuPoint.setInstallationAddress(Constants.STR_EMPTY);
        dtuPoint.setPositionLat(0d);
        dtuPoint.setPositionLon(0d);
        QueryWrapper<Dtu> queryPointWrapper = new QueryWrapper<>();
        queryPointWrapper.lambda().likeRight(Dtu::getIMEI, request.getImei() + "-")
                .eq(Dtu::getConsumerId, request.getConsumerId())
                .eq(Dtu::getSpId, spId)
                .eq(Dtu::getIsDeleted, Constants.IS_DELETED_FALSE);
        update = dtuMapper.selectList(queryPointWrapper).size();
        dtuMapper.update(dtuPoint, queryPointWrapper);
        //更新aep表
        DtuAep aep = new DtuAep();
        aep.setOpenTime("");
        aep.setOpenStatus(0);
        QueryWrapper<DtuAep> queryAepWrapper = new QueryWrapper<>();
        queryAepWrapper.lambda().likeRight(DtuAep::getIMEI, request.getImei() + "-")
                .eq(DtuAep::getSpId, spId)
                .eq(DtuAep::getIsDeleted, Constants.IS_DELETED_FALSE);
        dtuAepMapper.update(aep, queryAepWrapper);

        //更新 客户表设备数,点位数
        QueryWrapper<Consumer> queryConsumerWrapper = new QueryWrapper<>();
        queryConsumerWrapper.lambda().eq(Consumer::getId, request.getConsumerId())
                .eq(Consumer::getIsDeleted, Constants.IS_DELETED_FALSE)
                .eq(Consumer::getSpId, spId);
        Consumer consumerOld = this.getOne(queryConsumerWrapper);
        Consumer consumer = new Consumer();
        consumer.setEquipmentTotal(consumerOld.getEquipmentTotal() - 1);
        log.info("设备:{}解绑, 客户id={}, 原点位数={}, 减少点位数={}", request.getImei(), consumerOld.getId(), consumerOld.getPointTotal(), update);
        int pointTotal = consumerOld.getPointTotal() - update;
        if (pointTotal < 0) {
            log.info("客户的点位总数异常为{}", pointTotal);
            pointTotal = 0;
        }
        consumer.setPointTotal(pointTotal);
        this.update(consumer, queryConsumerWrapper);
        //更新客户设备数量信息
        consumerLocationService.updateConsumerLocationDeviceNum(spId,request.getConsumerId());

        //如果渠道二的客户或者智慧厨房紫荆报警器，解绑后没有任何设备, 删除客户
        if ((request.getTemplateType() == BIND_CHANNEL_ASST || Constants.ZJ_EQUIPMENT_FROM.equals(one.getEquipmentFrom())) && consumer.getEquipmentTotal() == 0) {
            log.info("销售单客户:{}当前已无绑定设备,进行逻辑删除", request.getConsumerId());
            Consumer consumerNew = new Consumer();
            consumerNew.setId(request.getConsumerId());
            consumerNew.setIsDeleted(true);
            this.updateById(consumerNew);
            //同步逻辑删除t_consumer_location表记录
            consumerLocationService.deleteConsumerLocation(spId,request.getConsumerId());
        }
        //同步解绑设备信息到tcis3.0
        this.syncUnbindEquipmentToTcis(request, consumerOld, spId);
        try {
            //操作日志log-20
            OperationLogVO logVO = new OperationLogVO();
            List<Integer> logCodeList = new ArrayList<>();
            logCodeList.add(OperationTypeEnum.OPERATION_TYPE_20.getCode());
            logVO.setCodeList(logCodeList);
            logVO.setTableName(TableConst.dtu.name());
            logVO.setTableKey(request.getImei());
            logVO.setSpId(spId);
            logVO.setOperationPersonCode(history.getOperationPersonCode());
            logVO.setOperationPersonName(history.getOperationPersonName());
            operationLogService.insertLog(logVO);
        } catch (Exception e) {
            log.info("unbindEquipment-error:{}",e);
        }
        HomeDeviceBindNoticeRequest requests = new HomeDeviceBindNoticeRequest();
        requests.setDeviceId(one.getDeviceCode());
        requests.setImei(request.getImei());
        if (Constants.ZJ_EQUIPMENT_FROM.equals(one.getEquipmentFrom())) {
            requests.setEquType(16);
        }else {
            requests.setEquType(19);
        }
        log.info("通知智慧厨房解绑 requests：" + requests.toString());
        String homeDeviceDelete = consoleSkFeignClient.homeDeviceUnBindNotice(requests);
        log.info("通知智慧厨房解绑 homeDeviceDelete：" + homeDeviceDelete);

        if (Constants.ZJ_EQUIPMENT_FROM.equals(one.getEquipmentFrom())) {
            //删除设备
            equipmentService.removeZJWifiDevice(request.getImei(), spId);
        }
        QueryWrapper<Dtu> queryDelWrapper = new QueryWrapper<>();
        queryDelWrapper.lambda().eq(Dtu::getParentImei, request.getImei())
                .eq(Dtu::getSpId, spId);
        List<Dtu> delList = dtuMapper.selectList(queryDelWrapper);
        for (Dtu dtu1 : delList) {
            log.info("删除报警小铃铛:" + dtu1.getIMEI());
            redisCacheExt.hashDel("alert_small_bell:" + spId, dtu1.getIMEI());
        }
        return "";
    }

    /**
     * 同步解绑设备信息到tcis
     * @param request
     * @param consumerOld
     * @param spId
     */
    private void syncUnbindEquipmentToTcis(ConsumerunBindingRequest request,
                                           Consumer consumerOld,
                                           String spId){
        try {
            log.info("syncUnbindEquipmentToTcis:ConsumerunBindingRequest:{},consumerOld:{},spId:{}",
                    JSONObject.toJSONString(request),
                    JSONObject.toJSONString(consumerOld),
                    spId);
            //非3.0退货安装且存在户号的解绑
            if ((null == request.getOperateType() || 3 != request.getOperateType()) && StringUtils.isNotEmpty(consumerOld.getSubsCode())) {
                //检查是否有来自TCIS的安装单
                LambdaQueryWrapper<WorkOrderHistory> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(WorkOrderHistory::getOrderType, 1)
                        .eq(WorkOrderHistory::getDeviceId, request.getImei())
                        .eq(WorkOrderHistory::getSubsCode, consumerOld.getSubsCode())
                        .eq(WorkOrderHistory::getSpId, spId)
                        .eq(WorkOrderHistory::getWorkSystem, 1);
                Integer tcisInstallCnt = workOrderHistoryService.getBaseMapper().selectCount(lambdaQueryWrapper);
                if (tcisInstallCnt > 0) {
                    UnbindAlarmRequest unbindAlarmRequest = new UnbindAlarmRequest();
                    unbindAlarmRequest.setUserid(consumerOld.getSubsCode());
                    unbindAlarmRequest.setResid(request.getImei());
                    tcisService.tcisRequestUnbindAlarm(unbindAlarmRequest, request.getConsumerId().toString(),spId);
                }
            }
        }catch(Exception e){
            log.error("同步解绑设备信息到tcis3.0失败：",e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void unbindMember(ConsumerunBindingRequest request) {
        String spId = ApplicationUtils.getWorkingSpId();
        if (StringUtils.isEmpty(spId)) {
            spId = request.getSpId();
        }
        log.info("spId的值为: {}", spId);
        //判断该imei设备是否存在且绑定该客户
        LambdaQueryWrapper<Dtu> dtuQueryWrapper = new LambdaQueryWrapper<>();
        dtuQueryWrapper.eq(Dtu::getIMEI, request.getImei())

                .eq(Dtu::getIsDeleted, Constants.IS_DELETED_FALSE);

        // 兼容APP端删除设备
        if (BIND_CHANNEL_ZJ_WIFI != request.getBindChannel()) {
            dtuQueryWrapper.eq(Dtu::getConsumerId, request.getConsumerId())
                    .eq(Dtu::getSpId, spId);
        }
        log.info("unbindEquipment dtuQueryWrapper: {}", dtuQueryWrapper.getTargetSql());
        Dtu one = equipmentService.getOne(dtuQueryWrapper);
        if (one == null) {
            log.error("unbindEquipment Dtu is empty request: {}", request);
            throw new BizException("该设备不存在或未绑定该客户.");
        }

        if (BIND_CHANNEL_ZJ_WIFI == request.getBindChannel()) {
            Consumer zjConsumer = baseMapper.selectById(one.getConsumerId());
            if (zjConsumer == null || zjConsumer.getMemberId().equals(request.getConsumerId())) {
                log.error("unbindEquipment zjConsumer is empty request: {}", request);
                throw new BizException("该设备不存在或未绑定该客户.");
            }
        }
        //新增设备解绑记录
        ConsumerDtuHistory history = new ConsumerDtuHistory();
        history.setId(null);
        history.setOutOrderCode(request.getOutOrderCode());
        history.setBindChannel(request.getTemplateType());
        history.setDeviceId(request.getImei());
        history.setEvent(0);
        history.setIMEI(request.getImei());
        history.setConsumerId(request.getConsumerId());
        if (request.getBindChannel().equals(BIND_CHANNEL_GAS)) {
            history.setOperationPersonCode(ApplicationUtils.getWorkingUser().getUsername());
            history.setOperationPersonName(ApplicationUtils.getWorkingUser().getName());
        } else if (request.getBindChannel().equals(BIND_CHANNEL_ASST)) {
            history.setOperationPersonCode("时刻助手销售单");
            history.setOperationPersonName("asst");
        } else if (request.getBindChannel().equals(BIND_CHANNEL_ZJ_WIFI)) {
            history.setOperationPersonCode("智慧厨房");
            history.setOperationPersonName("smartKitchen");
        }else {
            history.setOperationPersonCode("时刻助手销售单");
            history.setOperationPersonName("asst");
        }
        history.setRemark(Constants.STR_EMPTY);
        history.setSpId(spId);
        consumerDtuHistoryService.save(history);
        //删除服务信息
        consumerServiceInfoService.deleteConsumerServiceInfo(request.getImei());

        //查询当前企业下当前用户的所有设备
        LambdaQueryWrapper<Dtu> dtuMemberIdWrapper = new LambdaQueryWrapper<>();
        dtuMemberIdWrapper.eq(Dtu::getSpId, request.getSpId())
                .eq(Dtu::getIsDeleted, Constants.IS_DELETED_FALSE);
        List<Dtu> dtuList = equipmentService.list(dtuMemberIdWrapper);
        //更新 客户表
        QueryWrapper<Consumer> queryConsumerWrapper = new QueryWrapper<>();
        queryConsumerWrapper.lambda().eq(Consumer::getId, request.getConsumerId())
                .eq(Consumer::getIsDeleted, Constants.IS_DELETED_FALSE)
                .eq(Consumer::getSpId, spId);
        Consumer consumerOld = this.getOne(queryConsumerWrapper);
        Consumer consumer = new Consumer();
        consumer.setPhone("");
        this.update(consumer, queryConsumerWrapper);
        log.info("修改的客户的值为: {}", consumer);

        consumerLocationService.updateConsumerLocationDeviceNum(spId, request.getConsumerId());

        try {
            //操作日志log-20
            OperationLogVO logVO = new OperationLogVO();
            List<Integer> logCodeList = new ArrayList<>();
            logCodeList.add(OperationTypeEnum.OPERATION_TYPE_20.getCode());
            logVO.setCodeList(logCodeList);
            logVO.setTableName(TableConst.dtu.name());
            logVO.setTableKey(request.getImei());
            logVO.setSpId(spId);
            logVO.setOperationPersonCode(history.getOperationPersonCode());
            logVO.setOperationPersonName(history.getOperationPersonName());
            operationLogService.insertLog(logVO);
        } catch (Exception e) {
            log.info("unbindEquipment-error:{}",e);
        }
        QueryWrapper<Dtu> queryDelWrapper = new QueryWrapper<>();
        queryDelWrapper.lambda().eq(Dtu::getParentImei, request.getImei())
                .eq(Dtu::getSpId, spId);
        List<Dtu> delList = dtuMapper.selectList(queryDelWrapper);
        for (Dtu dtu1 : delList) {
            log.info("删除报警小铃铛:" + dtu1.getIMEI());
            redisCacheExt.hashDel("alert_small_bell:" + spId, dtu1.getIMEI());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void unbindEquipmentAsst(ConsumerunBindingRequest request) {
        String spId = ApplicationUtils.getWorkingSpId();
        // 判断 设备是否是完工提交的
        List<DtuBindingOrder> orderList = dtuBindingOrderMapper.selectAllByImei(request.getImei(), spId);
        log.info("被解绑设备的订单信息:", JSONObject.toJSONString(orderList));

        if (CollectionUtil.isEmpty(orderList)) {
            log.info("imei:{}, 不存在DtuBindingOrder表,或已删除", request.getImei());
            throw new BizException("设备:" + request.getImei() + "未完工提交");
        } else {
            unbindEquipment(request);
            //删除 DtuBindingOrder表对应数据
            for (DtuBindingOrder order : orderList) {
                DtuBindingOrder bindingOrder = new DtuBindingOrder();
                bindingOrder.setId(order.getId());
                bindingOrder.setIsDeleted(Boolean.TRUE);
                bindingOrder.setRealAddress(STR_EMPTY);
                dtuBindingOrderMapper.updateById(bindingOrder);
            }

            //操作日志log-20
            OperationLogVO logVO = new OperationLogVO();
            List<Integer> logCodeList = new ArrayList<>();
            logCodeList.add(OperationTypeEnum.OPERATION_TYPE_20.getCode());
            logVO.setCodeList(logCodeList);
            logVO.setTableName(TableConst.dtu.name());
            logVO.setTableKey(request.getImei());
            operationLogService.insertLog(logVO);

        }


    }

    @Override
    public EquipmentInfoResponse equipmentInfo(String imei) {
        String spId = ApplicationUtils.getWorkingSpId();
        List<String> spIds = organizationService.getSpIds(spId);
        // 询设备基本信息
        // 对于点型探测器的后缀进行截取
        String[] split = imei.split("-");
        imei = split[0];
        log.info("设备IMEI :{}", imei);
        QueryWrapper<Dtu> dtuQueryWrapper = new QueryWrapper<>();
        dtuQueryWrapper.lambda().eq(Dtu::getIMEI, imei).eq(Dtu::getIsDeleted, IS_DELETED_FALSE)
                .in(Dtu::getSpId, spIds);
        Dtu dtu = dtuMapper.selectOne(dtuQueryWrapper);
        if (dtu == null) {
            throw new BizException("该设备号imei不存在.");
        }
        EquipmentInfoResponse infoResponse = new EquipmentInfoResponse();
        BeanUtils.copyProperties(dtu, infoResponse);
        infoResponse.setEquipmentName(dtu.getName());
        infoResponse.setId(dtu.getDeviceCode());
        //紫荆设备的接收器、电磁阀信息
        if (dtu.getEquipmentFrom() == Constants.ZJ_EQUIPMENT_FROM) {
            LambdaQueryWrapper<ReceiverValve> lqw = new LambdaQueryWrapper<>();
            lqw.eq(ReceiverValve::getDeviceId, dtu.getIMEI()).in(ReceiverValve::getSpId, spIds)
                    .eq(ReceiverValve::getIsDeleted, Constants.IS_DELETED_FALSE);
            ReceiverValve receiverValve = receiverValveService.getOne(lqw);
            if (receiverValve != null) {
                infoResponse.setReceiverCode(receiverValve.getReceiverCode());
                infoResponse.setReceiverType(receiverValve.getReceiverType());
                infoResponse.setReceiverPowerMode(receiverValve.getReceiverPowerMode());
                infoResponse.setValveId(receiverValve.getValveId());
                infoResponse.setWithReceiver(true);
            } else {
                infoResponse.setWithReceiver(false);
            }
        }

        //设备厂商
        if (!StringUtils.isEmpty(dtu.getEquipmentManufacturer())) {
            //设备厂商名称
            ConsoleSkSupplierListResponse response = equipmentCmpService.supplierListRequest();
            log.info("调用厨房查询厂商接口返回：{}", response);
            List<AlarmSupplierListVo> supplierListVos = new ArrayList<>();
            if (response != null && response.getCode() == 0 && response.getData() != null && org.apache.commons.collections.CollectionUtils.isNotEmpty(response.getData())) {
                infoResponse.setEquipmentManufacturer(response.getData().stream().filter(a->a.getAlarmSystemCode().equals(
                        dtu.getEquipmentManufacturer())).collect(Collectors.toList()).get(0).getMsName());
            }
        }
        //设备type转name
        infoResponse.setEquipmentTypeName(dictionaryname(dtu.getEquipmentType(), "Equipment_type"));
        String operator = dictionaryname(dtu.getOperators(), "Operator");
        infoResponse.setOperators(operator);
        //检测类型存在多种;
        if (StrUtil.isNotBlank(dtu.getDetectionType())) {
            String[] typeList = dtu.getDetectionType().split(";");
            StringBuffer stringBuffer = new StringBuffer("");
            for (String type : typeList) {
                stringBuffer.append(dictionaryname(type, "Detection_type") + ";");
            }
            infoResponse.setDetectionType(stringBuffer.toString());
        }
        //判断设备类型, 控制器则统计点位数
        if (EquipmentType.GAS_ALARM_CONTROLLER.getCode().equals(dtu.getEquipmentType())) {
            //查询点位数
            QueryWrapper<Dtu> detectorQueryWrapper = new QueryWrapper<>();
            detectorQueryWrapper.lambda().likeRight(Dtu::getIMEI, imei + "-")
                    .in(Dtu::getSpId, spIds).eq(Dtu::getIsDeleted, IS_DELETED_FALSE);
            List<Dtu> dtuList = dtuMapper.selectList(detectorQueryWrapper);
            infoResponse.setPointAmount(dtuList.size());
            List<String> stringList = dtuList.stream().map(Dtu::getIMEI).collect(Collectors.toList());
            //控制器关联的点位IMEI集合
            infoResponse.setDetectorImeiList(stringList);
        } else if (EquipmentType.HOME_GAS_DETECTOR.getCode().equals(dtu.getEquipmentType()) ||
                //其他类型添加一个 IMEI-1-1的数据
                EquipmentType.INDEPENDENT_GAS_DETECTOR.getCode().equals(dtu.getEquipmentType())) {
            ArrayList<String> stringList = new ArrayList<>();
            //协议2.0 不再需要1-1查询
            stringList.add(dtu.getIMEI());
            infoResponse.setDetectorImeiList(stringList);
        }
        //实时状态, 区分不同协议
        LatestLog latestLog = latestLogService.get(dtu.getIMEI(), dtu.getSpId());
        if (latestLog.getEquipmentStatus() == null) {
            log.info("IMEI: {} 暂无实时状态数据", imei);
            infoResponse.setEquipmentStatus(null);
        } else {
            log.info("实时状态latestLog : {}", latestLog.toString());
            infoResponse.setEquipmentStatus(latestLog.getEquipmentStatus());
        }
        return infoResponse;
    }

    @Override
    public PageUtil<DtuMeasureLogResponse> dtuMeasureLog(EquipmentLogRequest request) {
        //充电中(协议2.0没有该数据) 显示"-"
        String spId = ApplicationUtils.getWorkingSpId();
        List<String> spIds = organizationService.getSpIds(spId);
        Dtu dtu = equipmentService.getDeviceByImeiAndSpIds(request.getImei(), spIds);
        return dtuMeasureLogV2(request, dtu, dtu.getSpId());
    }


    public PageUtil<DtuMeasureLogResponse> dtuMeasureLogV2(EquipmentLogRequest request, Dtu dtu, String spId) {
        //所属组织

        List<RecordController> list = new ArrayList<>();
        Page<Object> page = PageHelper.startPage(request.getPage(), request.getPageSize());
        if (StringUtils.isEmpty(request.getStartTime())) {
            log.info("查询RecordController");
            QueryWrapper<RecordController> recordWrapper = new QueryWrapper<>();
            recordWrapper.lambda().eq(RecordController::getDeviceId, dtu.getId())
                    .eq(RecordController::getConsumerId, request.getConsumerId())
                    .eq(RecordController::getSpId, spId)
                    .eq(RecordController::getIsDeleted, IS_DELETED_FALSE)
                    .orderByDesc(RecordController::getCreatedAt);
            list = recordControllerMapper.selectList(recordWrapper);
        } else {
            //查询近5个月内
            String month = StringUtils.substring(request.getStartTime(), 5, 7);
            log.info("查询RecordControllerHistory");
            List<RecordControllerHistory> historyList = controllerHistoryService.selectListByDevice(dtu.getId(), request.getConsumerId(), spId, month);
            for (RecordControllerHistory recordControllerHistory : historyList) {
                RecordController recordController = new RecordController();
                BeanUtils.copyProperties(recordControllerHistory,recordController);
                list.add(recordController);
            }
        }

        List<DtuMeasureLogResponse> resultList = new ArrayList<>();
        for (RecordController recordController : list) {
            //主电或备电故障, 总线也显示故障
            //当出现 其他故障, 主电备电状态不展示
            DtuMeasureLogResponse logResponse = new DtuMeasureLogResponse();
            if (recordController.getMainBatteryValue() != null) {
                if (recordController.getMainBatteryValue().equals(255)) {
                    logResponse.setVoltage("市电");
                } else if (recordController.getPowerModel() == 9) {
                    logResponse.setVoltage("-");
                } else {
                    logResponse.setVoltage(recordController.getMainBatteryValue() + "%");
                }

            }
            logResponse.setSignal(recordController.getSingal());  //与上一版本相同
            if (recordController.getControllerStatus() != null) {
                switch (recordController.getControllerStatus()) {
                    case 0:
                        logResponse.setBsB(false);
                        logResponse.setBpb(false);
                        logResponse.setMpb(false);
                        break;
                    case 17:
                        logResponse.setBsB(true);
                        logResponse.setBpb(false);
                        logResponse.setMpb(true);
                        break;
                    case 18:
                        logResponse.setBsB(true);
                        logResponse.setBpb(true);
                        logResponse.setMpb(false);
                        break;
                    case 19:
                        logResponse.setBsB(true);
                        break;
                }
            }

            logResponse.setCb(null);
            logResponse.setTime(recordController.getRecordAt());
            resultList.add(logResponse);
        }
        return new PageUtil(request.getPage(), request.getPageSize(), page.getTotal(), resultList);
    }

    public PageUtil<DtuMeasureLogResponse> dtuMeasureLogV1(EquipmentLogRequest request, String spId) {
        String path = departmentService.getPath(spId);
        List<DtuMeasureLogResponse> resultList = new ArrayList<>();
        //根据spId换path

        //获取数据库连接
        InfluxDBConnect influxDBConnect = influxDBConfiguration.getInfluxDBConnect();
        //查询 该IMEI指定月份内的所有通讯记录,根据时间倒序
        StringBuffer selectSql = new StringBuffer("select * from DataLogAsDetector where 1=1 and SubIdentifier = '__empty' ");

        String where = "and Path= '" + path + "' and DtuId= '" + request.getImei() + "' and "
                + "time >'" + request.getStartTime() + "' and time < '" + request.getEndTime() + "'";
        String sort = " order by time desc limit " + request.getPageSize() + " offset " + (request.getPage() - 1) * request.getPageSize();
        selectSql.append(where);
        selectSql.append(sort);
        log.info("selectSQL :{}", selectSql.toString());
        QueryResult queryResult = influxDBConnect.query(selectSql.toString());
        log.info("queryResult: {}", queryResult.toString());
        //查询 通讯记录总和
        String countSql = "select count(ConsumerId) from DataLogAsDetector where 1=1 and SubIdentifier = '__empty' " + where + "";
        log.info("countSql :{}", countSql);
        QueryResult countResult = influxDBConnect.query(countSql);
        log.info("countResult :{}", countResult);
        Integer count = 0;
        if (countResult.getResults().get(0).getSeries() != null) {
            String countStr = countResult.getResults().get(0).getSeries().get(0).getValues().get(0).get(1).toString();
            count = Integer.valueOf(countStr.substring(0, countStr.length() - 2));
        }
        List<List<Object>> dtuList = new ArrayList<>();
        if (queryResult.getResults().get(0).getSeries() != null) {
            dtuList = queryResult.getResults().get(0).getSeries().get(0).getValues();
        }
        for (List<Object> objects : dtuList) {
            log.info("------------- : {}", objects.get(8).toString());
            JSONObject jsonObject = JSON.parseObject(objects.get(8).toString());
            if (jsonObject.get("ver") != null) {
                DtuMeasureLogResponse logResponse = new DtuMeasureLogResponse();
                String btV = jsonObject.get("btV").toString();
                logResponse.setTime(DateUtil.parse(objects.get(0).toString()));
                logResponse.setVoltage(btV);
                logResponse.setBsB((Boolean) jsonObject.get("bsB"));  //总线情况
                logResponse.setMpb((Boolean) jsonObject.get("mpb")); //主电情况
                logResponse.setBpb((Boolean) jsonObject.get("bpb")); //备电
                logResponse.setCb((Boolean) jsonObject.get("cb"));  //充电
                logResponse.setSignal(SignalEnum.parse((Integer) jsonObject.get("si")).getLevel()); //信号
                resultList.add(logResponse);
            }
        }
        return new PageUtil(request.getPage(), request.getPageSize(), count, resultList);
    }


    @Override
    public PageUtil<DetectorMeasureLogResponse> detectorMeasureLog(EquipmentLogRequest request) {
        String spId = ApplicationUtils.getWorkingSpId();
        return detectorMeasureLogV2(request, spId);
    }


    public PageUtil<DetectorMeasureLogResponse> detectorMeasureLogV1(EquipmentLogRequest request, String spId) {
        String path = departmentService.getPath(spId);

        List<DetectorMeasureLogResponse> resultList = new ArrayList<>();
        String imei = StringUtils.substringBefore(request.getImei(), "-"); //截取 xxxx-1-11 的前缀
        String sub = StringUtils.substringAfter(request.getImei(), "-");   // 截取后缀
        //获取数据库连接
        InfluxDBConnect influxDBConnect = influxDBConfiguration.getInfluxDBConnect();
        //查询 该IMEI指定月份内的所有通讯记录,根据时间倒序
        StringBuffer selectSql = new StringBuffer("select * from DataLogAsDetector where 1=1 ");
        String where = "and Path= '" + path + "' and DtuId= '" + imei + "' and SubIdentifier ='" + sub + "'"
                + " and time >'" + request.getStartTime() + "' and time < '" + request.getEndTime() + "'";
        String sort = " order by time desc limit " + request.getPageSize() + " offset " + (request.getPage() - 1) * request.getPageSize();
        selectSql.append(where);
        selectSql.append(sort);

        log.info("selectSQL :{}", selectSql.toString());
        QueryResult queryResult = influxDBConnect.query(selectSql.toString());
        log.info("queryResult: {}", queryResult.toString());
        //查询 通讯记录总和
        String countSql = "select count(ConsumerId) from DataLogAsDetector where 1=1 " + where;
        QueryResult countResult = influxDBConnect.query(countSql);
        Integer count = 0;
        if (countResult.getResults().get(0).getSeries() != null) {
            String countStr = countResult.getResults().get(0).getSeries().get(0).getValues().get(0).get(1).toString();
            count = Integer.valueOf(countStr.substring(0, countStr.length() - 2));
        }
        log.info("countSql :{},count : {}", countSql, count);
        List<List<Object>> dtuList = new ArrayList<>();
        if (queryResult.getResults().get(0).getSeries() != null) {
            dtuList = queryResult.getResults().get(0).getSeries().get(0).getValues();
        }
        //检测类型dtu表查询, 独立探测器
        Dtu dtu = null;
        QueryWrapper<Dtu> dtuQueryWrapper = new QueryWrapper<>();
        dtuQueryWrapper.lambda().eq(Dtu::getIMEI, request.getImei())
                .eq(Dtu::getIsDeleted, Constants.IS_DELETED_FALSE)
                .eq(Dtu::getSpId, spId);
        dtu = dtuMapper.selectOne(dtuQueryWrapper);
        if (dtu == null) {
            // 家用报警器&独立报警器下的唯一点位 1-1
            QueryWrapper<Dtu> dtuQueryWrapper1 = new QueryWrapper<>();
            dtuQueryWrapper1.lambda().eq(Dtu::getIMEI, imei)
                    .eq(Dtu::getIsDeleted, Constants.IS_DELETED_FALSE)
                    .eq(Dtu::getSpId, spId);
            dtu = dtuMapper.selectOne(dtuQueryWrapper1);
        }
        for (List<Object> objects : dtuList) {
            //设备详细信息
            JSONObject jsonObject = JSON.parseObject(objects.get(8).toString());
            DetectorMeasureLogResponse logResponse = new DetectorMeasureLogResponse();
            logResponse.setTime(DateUtil.parse(objects.get(0).toString())); //时间
            logResponse.setXLEL(jsonObject.get("value").toString() + jsonObject.get("unit")); // 气体浓度
            //探头状态 0:离线 1:正常 2:低报 3:高报 4:故障 5:过期
            int status = (int) jsonObject.get("status");
            //默认都为正常
            logResponse.setBroken(false);
            if (status != 4) {
                logResponse.setAlarm(status);
            } else {
                logResponse.setBroken(true);
            }
            //检测类型存在多种;
            if (StrUtil.isNotBlank(dtu.getDetectionType())) {
                String[] typeList = dtu.getDetectionType().split(";");
                StringBuffer stringBuffer = new StringBuffer("");
                for (String type : typeList) {
                    stringBuffer.append(dictionaryname(type, "Detection_type") + ";");
                }
                logResponse.setDetectionType(stringBuffer.toString());
            }
            resultList.add(logResponse);
        }


        return new PageUtil(request.getPage(), request.getPageSize(), count, resultList);

    }

    public PageUtil<DetectorMeasureLogResponse> detectorMeasureLogV2(EquipmentLogRequest request, String spId) {
        //所属组织
        List<String> spIds = organizationService.getSpIds(spId);

        List<RecordDetector> list = new ArrayList<>();
        Page<Object> page = PageHelper.startPage(request.getPage(), request.getPageSize());
        if (StringUtils.isNotEmpty(request.getStartTime())) {
            log.info("查询RecordDetectorHistory");
            //查询大于5个月
            String month = StringUtils.substring(request.getStartTime(), 5, 7);
            List<RecordDetectorHistory> historyList = detectorHistoryService.selectListByDevice(request.getImei(), request.getConsumerId(), spIds, month);
            for (RecordDetectorHistory recordDetectorHistory : historyList) {
                RecordDetector recordDetector = new RecordDetector();
                BeanUtils.copyProperties(recordDetectorHistory,recordDetector);
                list.add(recordDetector);
            }
        } else {
            log.info("查询RecordDetector");
            QueryWrapper<RecordDetector> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(RecordDetector::getDeviceId, request.getImei())
                    .eq(RecordDetector::getConsumerId, request.getConsumerId())
                    .in(RecordDetector::getSpId, spIds)
                    .eq(RecordDetector::getIsDeleted, IS_DELETED_FALSE)
                    .orderByDesc(RecordDetector::getRecordAt);
            list = recordDetectorService.list(queryWrapper);
        }

        //数据处理
        ArrayList<DetectorMeasureLogResponse> logResponses = new ArrayList<>();
        for (RecordDetector record : list) {
            DetectorMeasureLogResponse response = new DetectorMeasureLogResponse();
            response.setTime(record.getRecordAt());
            String type = GasTypeEnum.getName(record.getGasType());
            response.setDetectionType(type);
            if (record.getConcentration() != null) {
                response.setXLEL(record.getConcentration() + CONCENTRATION_UNIT);
            }
            response.setAlarm(record.getAlertType());
            if (record.getDetectorStatus() != null) {
                if (DETECTOR_STATUS_32.equals(record.getDetectorStatus())
                        || DETECTOR_STATUS_33.equals(record.getDetectorStatus())
                        || DETECTOR_STATUS_34.equals(record.getDetectorStatus())
                        || DETECTOR_STATUS_35.equals(record.getDetectorStatus())
                        || VALVE_BROKEN_STATUS_70.equals(record.getDetectorStatus())) {
                    response.setBroken(true);
                } else if (DeviceConstant.DETECTOR_STATUS_0.equals(record.getDetectorStatus())) {
                    response.setBroken(false);
                }
            }

            logResponses.add(response);

        }

        return new PageUtil(request.getPage(), request.getPageSize(), page.getTotal(), logResponses);

    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchDeleteConsumer(List<String> request) {
        for (String s : request) {
            deleteConsumer(s);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HashMap<String, List<String>> importData(MultipartFile file) {
        String spId = ApplicationUtils.getWorkingSpId();
        //错误信息集合, key为行号, list为该行出现的错误
        HashMap<String, List<String>> errorMap = new HashMap<>();
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            throw new BizException("获取文件流失败");
        }
        //获得表头,  所有数据ExcelUtil.getReader("d:/aaa.xlsx");
        ExcelReader reader = ExcelUtil.getReader(inputStream, 0);
        List<List<Object>> read = reader.read(1, reader.getRowCount(), false);
        List<String> codeList = new ArrayList<>();
        List<String> imeiAllList = new ArrayList<>();
        //去除只有日期信息的行
        List<List<Object>> realRead = new ArrayList<>();
        for (List<Object> objects : read) {
            boolean areOtherColumnsNotEmpty = false;
            for (int j = 0; j < objects.size() -1; j++) {
                if (objects.get(j) != null) {
                    areOtherColumnsNotEmpty = true;
                    break;
                }
            }
            if (areOtherColumnsNotEmpty) {
                realRead.add(objects);
            } else {
                break;
            }
        }

        //行号 = 索引+1
        for (int i = 0; i < realRead.size(); i++) {
            log.info("开始校验行号:{} , 数据:{}", i + 2, read.get(i).toString());
            //校验信息汇总
            List<String> errorList = new ArrayList<>();
            List<Object> objects = read.get(i);
            //长度不足
            if (objects.size() < 34) {
                errorList.add(ConsumerUploadConst.DATE_NULL);
                log.info("行号:{}校验完毕, 错误信息:{}", i + 2, JSON.toJSONString(errorList));
                errorMap.put(Integer.toString(i + 2), errorList);
                continue;
            }
            String subsCode = objects.get(0) + "";
            String name = objects.get(1) + "";
            String industryType = objects.get(2) + "";
            //设备imei
            ArrayList<String> imeiList = new ArrayList<>();
            for (int j = 3; j <= 17; j += 3) {
                String IMEI = objects.get(j) + "";
                log.info("IMEI校验 :{}", IMEI);
                if (isNotNull(IMEI)) {
                    //设备imei号存在时, 校验安装位置存在
                    imeiList.add(IMEI);
                    if (isNull(objects.get(j + 1) + "")) {
                        errorList.add(ConsumerUploadConst.INSTALLATION_POSITION_NULL);
                    }
                    if (isNotNull(objects.get(j + 2) + "")) {
                        String valveName = objects.get(j + 2) + "";
                        //看电磁阀是否存在，是否被绑定
                        List<String> valveError = checkAndBindValve(valveName, IMEI);
                        errorList.addAll(valveError);
                    }
                }
            }
            //校验户号, 存在且未绑定
            if (!"null".equals(subsCode) && StringUtil.isNotEmpty(subsCode)) {
                List<String> subsCodeError = checkSubsCode(subsCode, spId);
                errorList.addAll(subsCodeError);
            }
            //检验 客户名格式
            if (!"null".equals(name) && StringUtil.isNotEmpty(name) && !name.matches("^(?!_)(?!.*?_$)[a-zA-Z0-9_\\u4e00-\\u9fa5]{2,32}$")) {
                errorList.add(ConsumerUploadConst.NAME_ILLEGAL);
            }
            //行业类型不为空,且在字典中
            List<String> industryTypeError = checkType(industryType);
            errorList.addAll(industryTypeError);
            //如果有imei,就校验imei号,不为空,未绑定, 存在
            if (!imeiList.isEmpty()) {
                List<String> imeiError = checkIMEI(imeiList, spId);
                errorList.addAll(imeiError);
            }
            //联系人
            ArrayList<String> telList = new ArrayList<>();
            List<String> contactError = new ArrayList<>();
            for (int a = 13; a <= 27; a = a + 3) {
                String contactName = objects.get(a) + "";
                String tel = objects.get(a + 1) + "";
                String level = objects.get(a + 2) + "";
                if (!"null".equals(tel) && StringUtil.isNotEmpty(tel)) {
                    telList.add(tel);
                }
                //校验 联系人字段, 三个字段同事存在或不存在, 手机号格式, 级别
                contactError.addAll(checkContact(contactName, tel, level));
            }
            //联系人电话不重复
            boolean isRepeat = telList.size() != new HashSet<>(telList).size();
            if (isRepeat) {
                contactError.add(ConsumerUploadConst.CONTACT_TELEPHONE_REPEAT);
            }
            errorList.addAll(contactError);
            //对错误信息去重
            if (CollectionUtil.isNotEmpty(errorList)) {
                errorMap.put(Integer.toString(i + 2), errorList.stream().distinct().collect(Collectors.toList()));
            }
            log.info("行号:{}校验完毕, 错误信息:{}", i + 2, JSON.toJSONString(errorList));
            if (isNotNull(subsCode)) {
                codeList.add(subsCode);
            }
            imeiAllList.addAll(imeiList);

        }
        //表中户号不重复,  设备号不重复
        ArrayList<String> infoErrorList = new ArrayList<>();
        if (codeList.size() != new HashSet<>(codeList).size()) {
            infoErrorList.add(ConsumerUploadConst.SUBS_REPEAT);
        }
        if (imeiAllList.size() != new HashSet<>(imeiAllList).size()) {
            infoErrorList.add(ConsumerUploadConst.IMEI_REPEAT);
        }
        if (CollectionUtil.isNotEmpty(infoErrorList)) {
            errorMap.put("info", infoErrorList);
        }

        //校验全部通过
        //新增导入记录
        FileUpload fileUpload = new FileUpload();
        fileUpload.setFileName(file.getOriginalFilename());
        fileUpload.setRowCount(read.size());
        fileUpload.setUploadTime(new Date());
        fileUpload.setUploadCreator(ApplicationUtils.getWorkingUser().getUsername());
        fileUpload.setCreatorName(ApplicationUtils.getWorkingUser().getName());
        fileUpload.setUploadCode("UPLOAD0002");
        fileUpload.setUploadUrl(fileUtil.uploadFile(file.getOriginalFilename(), file));
        fileUpload.setSpId(spId);
        // 存储错误信息
        fileUpload.setJsonInfo(JSON.toJSONString(errorMap));

        log.info("客户导入校验全部完成");

        //企业级日志
        LogVO vo = new LogVO();
        StringBuilder sb = new StringBuilder();
        if (CollectionUtil.isEmpty(errorMap)) {
            for (int i = 0; i < realRead.size(); i++) {
                Integer id = consumerImportAdd(realRead.get(i), 0, BIND_CHANNEL_GAS);
                sb.append("客户ID：").append(id);
                if (i != realRead.size() -1){
                    sb.append("\n");
                }
            }
            fileUpload.setUploadStatus("success");
            fileUploadMapper.insert(fileUpload);
            //操作日志log
            OperationLogVO logVO = new OperationLogVO();
            List<Integer> logCodeList = new ArrayList<>();
            logCodeList.add(OperationTypeEnum.OPERATION_TYPE_2.getCode());
            logVO.setCodeList(logCodeList);
            logVO.setTableName(TableConst.consumer.name());
            operationLogService.insertLog(logVO);
        } else {
            fileUpload.setUploadStatus("fail");
            fileUploadMapper.insert(fileUpload);
            sb.append("批量导入");
            vo.setResultCode(OPERATE_RESULT_FAIL);
        }

        vo.setCommonInfo(sb.toString());
        vo.setDetail("");
        LogRecordAspect.threadLocal.set(vo);

        return errorMap;
    }

    @Override
    public String importDataSync(MultipartFile file) {
        String spId = ApplicationUtils.getWorkingSpId();
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            throw new BizException("获取文件流失败");
        }
        log.info("importData-timeStart:{}", System.currentTimeMillis());
        String uuid = IdUtil.fastSimpleUUID();
        ExcelReader reader = ExcelUtil.getReader(inputStream, 0); //指定输入流和sheet
        log.info("importData-reader:{}", reader.toString());
        List<List<Object>> read = reader.read(1, reader.getRowCount(),false);
        log.info(uuid + " importData-read1111111:{}", JSONObject.toJSONString(read));
        String username = ApplicationUtils.getWorkingUser().getUsername();
        String applicationName = ApplicationUtils.getWorkingUser().getName();
        FileUpload fileUpload = new FileUpload();
        fileUpload = new FileUpload();
        fileUpload.setFileName(file.getOriginalFilename());
        fileUpload.setRowCount(read.size());
        fileUpload.setUploadTime(new Date());
        fileUpload.setUploadCreator(username);
        fileUpload.setCreatorName(applicationName);
        fileUpload.setUploadCode("UPLOAD0002");
        fileUpload.setSpId(spId);
        fileUpload.setUploadStatus("waiting");
        //上传文件路径
        String url = fileUtil.uploadFile(file.getOriginalFilename(), file);
        log.info(uuid + " importData-url:{}", JSONObject.toJSONString(url));
        fileUpload.setUploadUrl(url);
        fileUploadMapper.insert(fileUpload);
        log.info(uuid + " importData-fileUpload:{}", JSONObject.toJSONString(fileUpload));
        Integer id = fileUpload.getId();
        Integer resultCode = null;
        // 从主线程获取用户数据 放到局部变量中
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        SecurityContext context = SecurityContextHolder.getContext();
        executor.submit(() -> {
            try {
                // 把旧RequestAttributes放到新线程的RequestContextHolder中
                RequestContextHolder.setRequestAttributes(attributes);
                SecurityContextHolder.setContext(context);
                importConsumer(file, spId, read, username, applicationName, id, uuid);
            } catch (Exception e) {
                log.error(uuid + " importData-error:{}",e);
                FileUpload fileUpload1 = fileUploadMapper.selectById(id);
                if (fileUpload1 != null) {
                    fileUpload1.setUploadStatus("fail");
                    fileUploadMapper.updateById(fileUpload1);
                }
            }
        });
        LogVO vo = new LogVO();
        vo.setResultCode(Constants.OPERATE_RESULT_SUCCESS);
        LogRecordAspect.threadLocal.set(vo);
        log.info(uuid + " importData-return: {}", System.currentTimeMillis());
        return "";
    }

    private Integer importConsumer(MultipartFile file, String spId, List<List<Object>> read, String username, String applicationName, Integer id, String uuid) {
        //错误信息集合, key为行号, list为该行出现的错误
        HashMap<String, String> errorMap = new HashMap<>();
        log.info(uuid + " importDtu-start......");
        List<String> codeList = new ArrayList<>();
        List<String> imeiAllList = new ArrayList<>();
        List<Object> consumer = new ArrayList<>(); // 存储错误的导入客户，用于判断导入状态
        List<Integer> errors = new ArrayList<>(); // 存储错误行号；
        log.info(uuid + " importData-data:{}", JSONObject.toJSONString(read));
        //去除只有日期信息的行
        List<List<Object>> realRead = new ArrayList<>();
        for (List<Object> objects : read) {
            boolean areOtherColumnsNotEmpty = false;
            for (int j = 0; j < objects.size() - 1; j++) {
                if (objects.get(j) != null) {
                    areOtherColumnsNotEmpty = true;
                    break;
                }
            }
            if (areOtherColumnsNotEmpty) {
                realRead.add(objects);
            } else {
                break;
            }
        }
        if (realRead.size() == 0){
            errors.add(0);
            consumer.add(new Object());
            errorMap.put("0",ConsumerUploadConst.FORMAT_NULL);
        }

        FieldTemplate fieldTemplate = fieldTemplateMapper.getTypeBySpId(spId);
        Map<String,FuncArea> funcAreaMap = null;
        if( FUNC_AREA_ALLOCAT_CUSTOM.equals(fieldTemplate.getFuncAreaAllocat()) ){
            funcAreaMap = functionAreaService.getFuncAreaMapByName();
        }

        //行号 = 索引+1
        for (int i = 0; i < realRead.size(); i++) {
            log.info("开始校验行号:{} , 数据:{}", i + 2, read.get(i).toString());
            //校验信息汇总
            List<String> errorList = new ArrayList<>();
            List<Object> objects = read.get(i);
            try {
                //长度不足
                if (objects.size() < 38) {
                    errorList.add(ConsumerUploadConst.DATE_NULL);
                    log.info("行号:{}校验完毕, 错误信息:{}", i + 2, JSON.toJSONString(errorList));
                    errors.add(i + 2);
                    errorMap.put(Integer.toString(i + 2), errorList.toString());
                    consumer.add(read.get(i)); // 存储错误行
                    continue;
                }
                String subsCode = (objects.get(0) + "").trim();
                String orgCode = (objects.get(1) + "").trim();
                String name = (objects.get(2) + "").trim();
                String funAreaName = objects.get(3)==null?"":objects.get(3).toString().trim();
                if(!checkFunAreaField(funAreaName,funcAreaMap,"")){
                    errorList.add(ConsumerUploadConst.FUNC_AREA_ERROR);
                }
                String StreetName = objects.get(4)==null?"":objects.get(4).toString().trim();
                if(!checkFunAreaField(StreetName,funcAreaMap,funAreaName)){
                    errorList.add(ConsumerUploadConst.FUNC_STREET_ERROR);
                }
                String tradeAreaName = objects.get(5)==null?"":objects.get(5).toString().trim();
                if(!checkFunAreaField(tradeAreaName,funcAreaMap,"")){
                    errorList.add(ConsumerUploadConst.FUNC_TRADE_AREA_ERROR);
                }
                String industryType = (objects.get(6) + "").trim();
                //设备imei
                ArrayList<String> imeiList = new ArrayList<>();
                for (int j = 7; j <= 21; j += 3) {
                    String IMEI = (objects.get(j) + "").trim();
                    log.info("IMEI校验 :{}", IMEI);
                    if (isNotNull(IMEI)) {
                        //设备imei号存在时, 校验安装位置存在
                        imeiList.add(IMEI);
                        if (isNull(objects.get(j + 1) + "")) {
                            errorList.add(ConsumerUploadConst.INSTALLATION_POSITION_NULL);
                        }
                        if (isNotNull(objects.get(j + 2) + "")) {
                            String valveName = (objects.get(j + 2) + "").trim();
                            //看电磁阀是否存在，是否被绑定
                            List<String> valveError = checkAndBindValve(valveName, IMEI);
                            errorList.addAll(valveError);
                        }
                    }
                }
                //校验户号, 存在且未绑定
                if (!"null".equals(subsCode) && StringUtil.isNotEmpty(subsCode)) {
                    List<String> subsCodeError = checkSubsCodeC(subsCode, spId);
                    if ("null".equals(orgCode) || StringUtil.isEmpty(orgCode)){
                        subsCodeError.add(ConsumerUploadConst.COMPANY_NAME_NULL);
                    }
                    if (codeList.contains(subsCode)){
                        subsCodeError.add(ConsumerUploadConst.SUBS_REPEAT);
                    }
                    errorList.addAll(subsCodeError);
                }
                //检验 客户名格式
                if (!"null".equals(name) && StringUtil.isNotEmpty(name) && !name.matches("^(?!_)(?!.*?_$)[a-zA-Z0-9_\\u4e00-\\u9fa5]{2,32}$")) {
                    errorList.add(ConsumerUploadConst.NAME_ILLEGAL);
                }
                //行业类型不为空,且在字典中
                log.info("开始行业类型校验");
                List<String> industryTypeError = checkType(industryType,spId);
                errorList.addAll(industryTypeError);
                //如果有imei,就校验imei号,不为空,未绑定, 存在
                if (!imeiList.isEmpty()) {
                    List<String> imeiError = checkIMEI(imeiList, spId);
                    errorList.addAll(imeiError);
                }
                //联系人
                ArrayList<String> telList = new ArrayList<>();
                List<String> contactError = new ArrayList<>();
                for (int a = 22; a <= 36; a = a + 3) {
                    String contactName = (objects.get(a) + "").trim();
                    String tel = (objects.get(a + 1) + "").trim();
                    String level = (objects.get(a + 2) + "").trim();
                    if (!"null".equals(tel) && StringUtil.isNotEmpty(tel)) {
                        telList.add(tel);
                    }
                    //校验 联系人字段, 三个字段同事存在或不存在, 手机号格式, 级别
                    contactError.addAll(checkContact(contactName, tel, level));
                }
                //联系人电话不重复
                boolean isRepeat = telList.size() != new HashSet<>(telList).size();
                if (isRepeat) {
                    contactError.add(ConsumerUploadConst.CONTACT_TELEPHONE_REPEAT);
                }
                errorList.addAll(contactError);
                if (isNotNull(subsCode)) {
                    codeList.add(subsCode);
                }
                imeiAllList.addAll(imeiList);
            } catch (Exception e) {
                log.error(uuid + " importData-error:{}",e);
                errorList.add("校验失败");
            }
            //对错误信息去重
            if (CollectionUtil.isNotEmpty(errorList)) {
                errors.add(i + 2);
                errorMap.put(Integer.toString(i + 2), errorList.stream().distinct().collect(Collectors.toList()).toString());
                consumer.add(read.get(i));
            }
            log.info("行号:{}校验完毕, 错误信息:{}", i + 2, JSON.toJSONString(errorList));
        }
        //表中户号不重复,  设备号不重复
        ArrayList<String> infoErrorList = new ArrayList<>();
        if (codeList.size() != new HashSet<>(codeList).size()) {
            infoErrorList.add(ConsumerUploadConst.SUBS_REPEAT);
        }
        if (imeiAllList.size() != new HashSet<>(imeiAllList).size()) {
            infoErrorList.add(ConsumerUploadConst.IMEI_REPEAT);
        }
        if (CollectionUtil.isNotEmpty(infoErrorList)) {
            errorMap.put("info", infoErrorList.toString());
        }

        //校验全部通过
        //新增导入记录
        FileUpload fileUpload = new FileUpload();
        fileUpload.setFileName(file.getOriginalFilename());
        fileUpload.setRowCount(read.size());
        fileUpload.setUploadTime(new Date());
        fileUpload.setUploadCreator(username);
        fileUpload.setCreatorName(applicationName);
        fileUpload.setSpId(spId);
        fileUpload.setId(id);
        fileUpload.setUploadCode("UPLOAD0002");
        log.info("importData-fileUpload-pre:{}", JSONObject.toJSONString(fileUpload));
        //上传文件路径
//        String url = fileUtil.uploadFile(file.getOriginalFilename(), file);
//        log.info("importData-url:{}", JSONObject.toJSONString(url));
//        fileUpload.setUploadUrl(url);
        // 存储错误信息
        List<Map<String, String>> jsonList = new ArrayList<>();
        log.info("importData-errors:{}", JSONObject.toJSONString(errors));
        try {
            if (!CollectionUtil.isEmpty(errors)) {
                errorMap.forEach((integer, s) -> {
                    Map<String, String> res = new HashMap<>();
                    res.put("number", integer);
                    res.put("reason", s.replace("[","").replace("]",""));
                    jsonList.add(res);
                });
            }
            fileUpload.setJsonInfo(JSONObject.toJSONString(jsonList));
            log.info("importData-fileUploadMapper:{}", JSONObject.toJSONString(fileUpload));
        } catch (Exception e) {
            log.info("insert-error:{}", e);
        }
        log.info("importData-fileUpload:{}", JSONObject.toJSONString(fileUpload));
        log.info("客户导入校验全部完成");

        //企业级日志
        LogVO vo = new LogVO();
        StringBuilder sb = new StringBuilder();
        OperationLogVO logVO = new OperationLogVO();
        List<Integer> logCodeList = new ArrayList<>();
        Integer resultCode = 1;
        if (CollectionUtil.isEmpty(errorMap) && CollectionUtil.isEmpty(consumer)) {
            try {
                for (int i = 0; i < realRead.size(); i++) {
                    Integer consumerId = consumerImportAdd(realRead.get(i), 0, BIND_CHANNEL_GAS,spId, funcAreaMap);
                    sb.append("客户ID：").append(consumerId);
                    if (i != realRead.size() - 1) {
                        sb.append("\n");
                    }
                }
                fileUpload.setUploadStatus("success");
            } catch (Exception e) {
                log.error(uuid + " importData-error:{}",e);
                fileUpload.setUploadStatus("fail");
            }
            fileUploadMapper.updateById(fileUpload);
        } else if (consumer.size() < realRead.size()) {
            try {
                for (int i = 0; i < realRead.size(); i++) {
                    if (!errors.contains(i + 2)) {
                        //发起
                        Integer consumerId = consumerImportAdd(realRead.get(i), 0, BIND_CHANNEL_GAS, spId, funcAreaMap);

                        sb.append("客户ID:").append(consumerId);
                        if (i != realRead.size() - 1) {
                            sb.append("\n");
                        }
                    }
                }
                resultCode = OPERATE_RESULT_SUCCESS_PART;
                fileUpload.setUploadStatus("part_success");
            } catch (Exception e) {
                log.error(uuid + " importData-error:{}",e);
                fileUpload.setUploadStatus("fail");
            }
            fileUploadMapper.updateById(fileUpload);
            sb.append("批量导入部分成功");
            vo.setResultCode(OPERATE_RESULT_SUCCESS_PART);
        } else {
            resultCode = OPERATE_RESULT_FAIL;
            fileUpload.setUploadStatus("fail");
            fileUploadMapper.updateById(fileUpload);
            sb.append("批量导入");
            vo.setResultCode(OPERATE_RESULT_FAIL);
        }

        vo.setCommonInfo(sb.toString());
        //操作日志log
        LogRecordAspect.threadLocal.set(vo);
        logCodeList.add(OperationTypeEnum.OPERATION_TYPE_2.getCode());
        logVO.setCodeList(logCodeList);
        logVO.setTableName(TableConst.consumer.name());
        operationLogService.insertLog(logVO);

        return resultCode;
    }

    /**
     * 校验功能区字段
     * 校验功能区字段
     * @param name
     * @param funcAreaMap
     * @return
     */
    private boolean checkFunAreaField(String name,Map<String,FuncArea> funcAreaMap,String parentName){
        if( StringUtils.isEmpty(name) ){
            return true;
        }else if( null==funcAreaMap || funcAreaMap.isEmpty()){
            return true;
        }else if(funcAreaMap.containsKey(name)){
            if( StringUtils.isEmpty(parentName) ){
                return true;
            }else if( !funcAreaMap.containsKey(parentName) ){
                return false;
            }else if(!Objects.equals(funcAreaMap.get(parentName).getId(), funcAreaMap.get(name).getPid())){
                return false;
            }
            return true;
        }else{
            return false;
        }
    }

    private List<String> checkAndBindValve(String valveName, String imei) {
        List<String> list = new ArrayList<>();
        LambdaQueryWrapper<ValveInfo> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ValveInfo::getValveName, valveName).eq(ValveInfo::getIsDeleted, IS_DELETED_FALSE);
        List<ValveInfo> valveInfoList = valveInfoService.list(lqw);
        if(CollectionUtils.isEmpty(valveInfoList)){
            //电磁阀不存在
            list.add(valveName + ConsumerUploadConst.VALVE_EXIST_ERROR );
            return list;
        }
        LambdaQueryWrapper<Dtu> dtuLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dtuLambdaQueryWrapper.eq(Dtu::getIMEI, imei).eq(Dtu::getIsDeleted, IS_DELETED_FALSE);
        Dtu dtu = dtuMapper.selectOne(dtuLambdaQueryWrapper);
        if(dtu != null){
            if (dtu.getValveInfoId() != 0 && !dtu.getValveInfoId().equals(valveInfoList.get(0).getId())){
                //设备已绑定其他电磁阀
                list.add(valveName + ConsumerUploadConst.VALVE_BIND_ERROR);
            }
            DeviceSolenoidRequest bindingRequest = new DeviceSolenoidRequest();
            bindingRequest.setImei(imei);
            bindingRequest.setSolenoidId(valveInfoList.get(0).getId());
            bindingRequest.setOptType(0);
            deviceSolenoidService.updateDeviceSolenoid(bindingRequest);
        }
        return list;
    }

    public boolean isNotNull(String str) {
        return (!"null".equals(str) && StringUtil.isNotEmpty(str));
    }

    public boolean isNull(String str) {
        return ("null".equals(str) || StringUtil.isEmpty(str));
    }

    @Override
    public List<String> checkSubsCode(String subsCode, String spId) {
        List<String> list = new ArrayList<>();
        //判断是否存在客户表
        QueryWrapper<Consumer> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Consumer::getSpId, spId)
                .eq(Consumer::getIsDeleted, Constants.IS_DELETED_FALSE)
                .eq(Consumer::getSubsCode, subsCode);
        if (CollectionUtil.isNotEmpty(this.list(queryWrapper))) {
            list.add(ConsumerUploadConst.SUBS_CREATED);
        }

        VccUserRseponse vccUser = getVccUser(subsCode,"",null);
        if (vccUser == null) {
            list.add(ConsumerUploadConst.SUBS_NO_FOUND);
        }
        return list;
    }

    public List<String> checkSubsCodeC(String subsCode, String spId) {
        List<String> list = new ArrayList<>();
        //判断是否存在客户表
        QueryWrapper<Consumer> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Consumer::getSpId, spId)
                .eq(Consumer::getIsDeleted, Constants.IS_DELETED_FALSE)
                .eq(Consumer::getSubsCode, subsCode);
        if (CollectionUtil.isNotEmpty(this.list(queryWrapper))) {
            list.add(ConsumerUploadConst.SUBS_CREATED);
        }

        VccUserRseponse vccUser = getVccUserC(subsCode, spId, null);
        log.info("VccUserRseponse: {}", vccUser);
        if (vccUser == null || StringUtils.isEmpty(vccUser.getSubsCode())) {
            list.add(ConsumerUploadConst.SUBS_NO_FOUND);
        }
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer installImportAdd(List<Object> objects, int offset, Integer bindChannel, Map<String,FuncArea> funcAreaMap) {
        log.info("installImportAdd---start");

        ConsumerRequest request = new ConsumerRequest();
        //根据户号获得户表字段,
        String subsCode = String.valueOf(objects.get(0)).trim();
        String name = String.valueOf(objects.get(1)).trim();
        ConsumerFuncAreaRequest consumerFuncAreaRequest = new ConsumerFuncAreaRequest();
        String funcAreaName = String.valueOf(objects.get(2)).trim();
        String streetName = String.valueOf(objects.get(3)).trim();
        String tradeAreaName = String.valueOf(objects.get(4)).trim();
        if ( ObjectUtil.isNotEmpty(funcAreaName) && null!=funcAreaMap && funcAreaMap.containsKey(funcAreaName)){
            consumerFuncAreaRequest.setDistrictCode(funcAreaMap.get(funcAreaName).getFuncCode());
        }
        if ( ObjectUtil.isNotEmpty(streetName) && null!=funcAreaMap && funcAreaMap.containsKey(streetName)){
            consumerFuncAreaRequest.setStreetCode(funcAreaMap.get(streetName).getFuncCode());
        }
        if ( ObjectUtil.isNotEmpty(tradeAreaName) && null!=funcAreaMap && funcAreaMap.containsKey(tradeAreaName)){
            consumerFuncAreaRequest.setBusinessAreaCode(funcAreaMap.get(tradeAreaName).getFuncCode());
        }
        if( null!=funcAreaMap ){
            request.setFuncAreaAllocat(FUNC_AREA_ALLOCAT_CUSTOM);
        }
        request.setFuncArea(consumerFuncAreaRequest);
        String industryType = String.valueOf(objects.get(5)).trim();
        List<DictionaryItemRespDTO> dictionary = holder.getDictionaryByKey(Constants.INDUSTRY_TYPE_CODE);
        List<DictionaryItemRespDTO> dtos = dictionary.stream().filter(dto -> dto.getName().equals(industryType)).collect(Collectors.toList());
        if (isNotNull(name)) {
            request.setName(name);
        }
        request.setIndustryType(dtos.get(0).getValue());
        request.setAdCode("0"); //默认为 0
        if (!"null".equals(subsCode)) {

            VccUserRseponse vccUser = getVccUser(subsCode,"",null);

            if (vccUser != null) {
                BeanUtils.copyProperties(vccUser, request);
                String statusName = CustStatusEnum.getCustStatusName(vccUser.getCustStatus());
                //获取经纬度
                request = mapGeoCoding(request);
                request.setCustType(queryDictMapByCodeNoSpId(CUST_TYPE_ENUM , CustTypeEnum.toMap()).get(vccUser.getCustType()));
                request.setCustTypeCode(vccUser.getCustType());
                request.setCustStatus(statusName);
                request.setAddress(request.getCustAddress());
            }
        }


        //将联系人设置为入参
        List<ContactsRequest> contactsList = new ArrayList<>();
        for (int a = 16 + offset; a <= 30 + offset; a = a + 3) {
            String contactName = (objects.get(a) + "").trim();
            String tel = (objects.get(a + 1) + "").trim();
            String level = (objects.get(a + 2) + "").trim();
            if (isNotNull(contactName) && isNotNull(tel) && isNotNull(level)) {
                ContactsRequest contact = new ContactsRequest();
                contact.setName(contactName);
                contact.setTelephone(tel);
                contact.setLevel(Integer.parseInt(level));
                contactsList.add(contact);
            }
        }
        request.setContactsList(contactsList);
        //新增客户,获取id
        request.setType(1);
        Integer id = this.addConsumer(request);
        //新增客户,获取id

        ArrayList<BindingPositionRequest> imeiList = new ArrayList<>();
        for (int j = 6 + offset; j <= 15 + offset; j += 3) {
            String IMEI = String.valueOf(objects.get(j)).trim();
            String installationPosition = String.valueOf(objects.get(j + 1)).trim();
            if (isNotNull(IMEI) && isNotNull(installationPosition)) {
                BindingPositionRequest positionRequest = new BindingPositionRequest();
                positionRequest.setImei(IMEI);
                positionRequest.setInstallationPosition(installationPosition);
                imeiList.add(positionRequest);
            }

        }

        if (CollectionUtil.isNotEmpty(imeiList)) {
            ConsumerBindingRequest bindingRequest = new ConsumerBindingRequest();
            bindingRequest.setConsumerId(id);
            bindingRequest.setImeiList(imeiList);
            bindingRequest.setBindChannel(bindChannel);
            //新增绑定设备
            this.importAZBindingEquipment(bindingRequest);
        }
        return id;


    }
    @Transactional(rollbackFor = Exception.class)
    public Integer installImportAdd(List<Object> objects, int offset, Integer bindChannel,String spId) {
        log.info("installImportAdd---start");

        ConsumerRequest request = new ConsumerRequest();
        //根据户号获得户表字段,
        String subsCode = String.valueOf(objects.get(0));
        String name = String.valueOf(objects.get(1));
        String industryType = String.valueOf(objects.get(2));
        List<DictionaryItemRespDTO> dictionary = holder.getDictionaryByKey(Constants.INDUSTRY_TYPE_CODE,spId);
        List<DictionaryItemRespDTO> dtos = dictionary.stream().filter(dto -> dto.getName().equals(industryType)).collect(Collectors.toList());
        if (isNotNull(name)) {
            request.setName(name);
        }
        request.setIndustryType(dtos.get(0).getValue());
        request.setAdCode("0"); //默认为 0
        if (!"null".equals(subsCode)) {

            VccUserRseponse vccUser = getVccUser(subsCode, "", null);

            if (vccUser != null) {
                BeanUtils.copyProperties(vccUser, request);
                String statusName = CustStatusEnum.getCustStatusName(vccUser.getCustStatus());
                //获取经纬度
                request = mapGeoCoding(request);
                request.setCustType(queryDictMapByCodeNoSpId(CUST_TYPE_ENUM,CustTypeEnum.toMap()).get(vccUser.getCustType()));
                request.setCustTypeCode(vccUser.getCustType());
                request.setCustStatus(statusName);
                request.setAddress(request.getCustAddress());
            }
        }


        //将联系人设置为入参
        List<ContactsRequest> contactsList = new ArrayList<>();
        for (int a = 13 + offset; a <= 27 + offset; a = a + 3) {
            String contactName = objects.get(a) + "";
            String tel = objects.get(a + 1) + "";
            String level = objects.get(a + 2) + "";
            if (isNotNull(contactName) && isNotNull(tel) && isNotNull(level)) {
                ContactsRequest contact = new ContactsRequest();
                contact.setName(contactName);
                contact.setTelephone(tel);
                contact.setLevel(Integer.parseInt(level));
                contactsList.add(contact);
            }
        }
        request.setContactsList(contactsList);
        //新增客户,获取id
        request.setType(1);
        Integer id = this.addConsumer(request,spId);
        //新增客户,获取id

        ArrayList<BindingPositionRequest> imeiList = new ArrayList<>();
        for (int j = 3 + offset; j <= 12 + offset; j += 3) {
            String IMEI = String.valueOf(objects.get(j));
            String installationPosition = String.valueOf(objects.get(j + 1));
            if (isNotNull(IMEI) && isNotNull(installationPosition)) {
                BindingPositionRequest positionRequest = new BindingPositionRequest();
                positionRequest.setImei(IMEI);
                positionRequest.setInstallationPosition(installationPosition);
                imeiList.add(positionRequest);
            }

        }

        if (CollectionUtil.isNotEmpty(imeiList)) {
            ConsumerBindingRequest bindingRequest = new ConsumerBindingRequest();
            bindingRequest.setConsumerId(id);
            bindingRequest.setImeiList(imeiList);
            bindingRequest.setBindChannel(bindChannel);
            //新增绑定设备
            this.bindingEquipment(bindingRequest);
        }
        return id;


    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer consumerImportAdd(List<Object> objects, int offset, Integer bindChannel) {
        log.info("consumerImportAdd---start");
        ConsumerRequest request = new ConsumerRequest();
        //根据户号获得户表字段,
        String subsCode = String.valueOf(objects.get(0));
        String name = String.valueOf(objects.get(1));
        String industryType = String.valueOf(objects.get(2));
        List<DictionaryItemRespDTO> dictionary = holder.getDictionaryByKey(Constants.INDUSTRY_TYPE_CODE);
        List<DictionaryItemRespDTO> dtos = dictionary.stream().filter(dto -> dto.getName().equals(industryType)).collect(Collectors.toList());
        if (isNotNull(name)) {
            request.setName(name);
        }
        request.setIndustryType(dtos.get(0).getValue());
        request.setAdCode("0"); //默认为 0
        if (!"null".equals(subsCode)) {

            VccUserRseponse vccUser = getVccUser(subsCode,"",null);

            if (vccUser != null) {
                BeanUtils.copyProperties(vccUser, request);
                String statusName = CustStatusEnum.getCustStatusName(vccUser.getCustStatus());
                //获取经纬度
                request = mapGeoCoding(request);
                request.setCustType(queryDictMapByCodeNoSpId(CUST_TYPE_ENUM,CustTypeEnum.toMap()).get(vccUser.getCustType()));
                request.setCustTypeCode(vccUser.getCustType());
                request.setCustStatus(statusName);
                request.setAddress(request.getCustAddress());
            }
        }


        //将联系人设置为入参
        List<ContactsRequest> contactsList = new ArrayList<>();
        for (int a = 18 + offset; a <= 30 + offset; a = a + 3) {
            String contactName = objects.get(a) + "";
            String tel = objects.get(a + 1) + "";
            String level = objects.get(a + 2) + "";
            if (isNotNull(contactName) && isNotNull(tel) && isNotNull(level)) {
                ContactsRequest contact = new ContactsRequest();
                contact.setName(contactName);
                contact.setTelephone(tel);
                contact.setLevel(Integer.parseInt(level));
                contactsList.add(contact);
            }
        }
        request.setContactsList(contactsList);
        //新增客户,获取id
        request.setType(1);
        Integer id = this.addConsumer(request);
        //新增客户,获取id

        ArrayList<BindingPositionRequest> imeiList = new ArrayList<>();
        for (int j = 3 + offset; j <= 17 + offset; j += 3) {
            String IMEI = String.valueOf(objects.get(j));
            String installationPosition = String.valueOf(objects.get(j + 1));
            if (isNotNull(IMEI) && isNotNull(installationPosition)) {
                BindingPositionRequest positionRequest = new BindingPositionRequest();
                positionRequest.setImei(IMEI);
                positionRequest.setInstallationPosition(installationPosition);
                imeiList.add(positionRequest);
            }

        }

        if (CollectionUtil.isNotEmpty(imeiList)) {
            ConsumerBindingRequest bindingRequest = new ConsumerBindingRequest();
            bindingRequest.setConsumerId(id);
            bindingRequest.setImeiList(imeiList);
            bindingRequest.setBindChannel(bindChannel);
            //新增绑定设备
            this.bindingEquipment(bindingRequest);
        }
        return id;


    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer consumerImportAdd(List<Object> objects, int offset, Integer bindChannel, String spId, Map<String, FuncArea> funcAreaMap) {
        log.info("consumerImportAdd---start");
        ConsumerRequest request = new ConsumerRequest();
        //根据户号获得户表字段,
        String subsCode = String.valueOf(objects.get(0)).trim();
        String orgCode = String.valueOf(objects.get(1)).trim();
        String name = String.valueOf(objects.get(2)).trim();
        ConsumerFuncAreaRequest consumerFuncAreaRequest = new ConsumerFuncAreaRequest();
        String funcAreaName = String.valueOf(objects.get(3)).trim();
        String streetName = String.valueOf(objects.get(4)).trim();
        String tradeAreaName = String.valueOf(objects.get(5)).trim();
        if ( ObjectUtil.isNotEmpty(funcAreaName) && null!=funcAreaMap && funcAreaMap.containsKey(funcAreaName)){
            consumerFuncAreaRequest.setDistrictCode(funcAreaMap.get(funcAreaName).getFuncCode());
        }
        if ( ObjectUtil.isNotEmpty(streetName) && null!=funcAreaMap && funcAreaMap.containsKey(streetName)){
            consumerFuncAreaRequest.setStreetCode(funcAreaMap.get(streetName).getFuncCode());
        }
        if ( ObjectUtil.isNotEmpty(tradeAreaName) && null!=funcAreaMap && funcAreaMap.containsKey(tradeAreaName)){
            consumerFuncAreaRequest.setBusinessAreaCode(funcAreaMap.get(tradeAreaName).getFuncCode());
        }
        if( null!=funcAreaMap ){
            request.setFuncAreaAllocat(FUNC_AREA_ALLOCAT_CUSTOM);
        }
        request.setFuncArea(consumerFuncAreaRequest);
        String industryType = String.valueOf(objects.get(6)).trim();
        List<DictionaryItemRespDTO> dictionary = holder.getDictionaryByKey(Constants.INDUSTRY_TYPE_CODE,spId);
        List<DictionaryItemRespDTO> dtos = dictionary.stream().filter(dto -> dto.getName().equals(industryType)).collect(Collectors.toList());
        if (isNotNull(name)) {
            request.setName(name);
        }
        // 根据拿到的orgCode去对比字典表，换成真正的Code
        ArrayList<String> list = new ArrayList<>();
        list.add(spId);
        list.add("0");
        if ( !"null".equals(orgCode) && StringUtils.isNotEmpty(orgCode) ) {
            QueryWrapper<Dictionary> dictionaryQueryWrapper = new QueryWrapper<>();
            dictionaryQueryWrapper.lambda()
                    .eq(Dictionary::getIsDeleted, IS_DELETED_FALSE)
                    .in(BaseEntity::getSpId, list)
                    .eq(Dictionary::getDictCode, "org_map_subsCode")
                    .eq(Dictionary::getCompanyName, orgCode);
            List<Dictionary> dictionaryList = dictionaryMapper.selectList(dictionaryQueryWrapper);
            if (!CollectionUtils.isEmpty(dictionaryList)) {
                if (dictionaryList.get(0).getCompanyName().equals(orgCode)) {
                    orgCode = dictionaryList.get(0).getDescription();
                    request.setOrgCode(orgCode);
                }
            }
        }
        request.setIndustryType(dtos.get(0).getValue());
        request.setAdCode("0"); //默认为 0
        if (!"null".equals(subsCode)) {

            VccUserRseponse vccUser = getVccUser(subsCode, spId, null);

            if (vccUser != null) {
                BeanUtils.copyProperties(vccUser, request);
                String statusName = CustStatusEnum.getCustStatusName(vccUser.getCustStatus());
                //获取经纬度
                request = mapGeoCoding(request);
                request.setCustType(queryDictMapByCodeNoSpId(CUST_TYPE_ENUM,CustTypeEnum.toMap()).get(vccUser.getCustType()));
                request.setCustTypeCode(vccUser.getCustType());
                request.setCustStatus(statusName);
                request.setAddress(request.getCustAddress());
            }
        }

        //将联系人设置为入参
        List<ContactsRequest> contactsList = new ArrayList<>();
        for (int a = 22 + offset; a <= 36 + offset; a = a + 3) {
            String contactName = (objects.get(a) + "").trim();
            String tel = (objects.get(a + 1) + "").trim();
            String level = (objects.get(a + 2) + "").trim();
            if (isNotNull(contactName) && isNotNull(tel) && isNotNull(level)) {
                ContactsRequest contact = new ContactsRequest();
                contact.setName(contactName);
                contact.setTelephone(tel);
                contact.setLevel(Integer.parseInt(level));
                contactsList.add(contact);
            }
        }
        request.setContactsList(contactsList);
        //新增客户,获取id
        request.setType(1);
        Integer id = this.addConsumer(request,spId);
        //新增客户,获取id

        ArrayList<BindingPositionRequest> imeiList = new ArrayList<>();
        for (int j = 7 + offset; j <= 21 + offset; j += 3) {
            String IMEI = String.valueOf(objects.get(j)).trim();
            String installationPosition = String.valueOf(objects.get(j + 1)).trim();
            if (isNotNull(IMEI) && isNotNull(installationPosition)) {
                BindingPositionRequest positionRequest = new BindingPositionRequest();
                positionRequest.setImei(IMEI);
                positionRequest.setInstallationPosition(installationPosition);
                imeiList.add(positionRequest);
            }

        }

        if (CollectionUtil.isNotEmpty(imeiList)) {
            ConsumerBindingRequest bindingRequest = new ConsumerBindingRequest();
            bindingRequest.setConsumerId(id);
            bindingRequest.setImeiList(imeiList);
            bindingRequest.setBindChannel(bindChannel);
            bindingRequest.setSpId(spId);
            //新增绑定设备
            this.importBindingEquipment(bindingRequest);
        }
        return id;


    }
    @Override
    public VccUserRseponse getVccUser(String subsCode,String spId,String  orgCode) {
        log.info("getVccUser-params:{},{}",subsCode,spId);
        VccUserRseponse response = new VccUserRseponse();
        try {
            cn.hutool.json.JSONObject vccUser =null;
            if (StringUtils.isBlank(orgCode)){
                List<String>  orgCodes = companyService.getOrgCodeBySubsCode(StringUtils.isBlank(spId)?ApplicationUtils.getWorkingSpId():spId);
                log.info("orgCodes:" + orgCodes);
                for (String code : orgCodes) {
                    try {
                        vccUser = vccAuthoritiesProvider.getVccUser(code, subsCode);
                        log.info("getVccUser-vccUser:{}",JSONObject.toJSON(vccUser));
                    } catch (Exception e) {
                        log.error("getVccUser-error:{}",e);
                    }
                    if (vccUser != null) break;
                }
            }else{
                 vccUser = vccAuthoritiesProvider.getVccUser(orgCode, subsCode);

            }

            if (vccUser == null) {
                return null;
            }
            log.info("vccUser :{}", vccUser.toString());
            response.setCustName(vccUser.get("name").toString());
            response.setSubsCode(vccUser.get("subsCode").toString());
            response.setCustPhone(vccUser.get("phone").toString());
            response.setCustAddress(vccUser.get("displayAddr").toString());
            response.setCustType(vccUser.get("subsType").toString());
            response.setCustStatus(vccUser.get("state").toString());
        } catch (GlobalAuthenticationException e) {
            log.info("获取vcc户表信息失败, 户号:{}", subsCode);
            return null;
        }
        return response;
    }

    public VccUserRseponse getVccUserC(String subsCode, String spId, String orgCode) {
        log.info("getVccUser-params:{},{}", subsCode, spId);
        VccUserRseponse response = new VccUserRseponse();
        cn.hutool.json.JSONObject vccUser = null;
        if (StringUtils.isBlank(orgCode)) {
            List<String> orgCodes = companyService.getOrgCodeBySubsCode(StringUtils.isBlank(spId) ? ApplicationUtils.getWorkingSpId() : spId);
            log.info("orgCodes:" + orgCodes);
            for (String code : orgCodes) {
                vccUser = vccAuthoritiesProvider.getVccUserC(code, subsCode);
                log.info("getVccUser-vccUser:{}", JSONObject.toJSON(vccUser));
                if (vccUser != null) break;
            }
        } else {
            vccUser = vccAuthoritiesProvider.getVccUserC(orgCode, subsCode);

        }

        if (vccUser == null) {
            return null;
        }
        log.info("vccUser :{}", vccUser.toString());
        log.info("vccUser.get:{}",vccUser.get("name"));
        if (vccUser.get("name") != null) {
            response.setCustName(vccUser.get("name").toString());
            response.setSubsCode(vccUser.get("subsCode").toString());
            response.setCustPhone(vccUser.get("phone").toString());
            response.setCustAddress(vccUser.get("displayAddr").toString());
            response.setCustType(vccUser.get("subsType").toString());
            response.setCustStatus(vccUser.get("state").toString());
        }
        return response;
    }

    @Override
    public String updateVccUser(String subsCode, String consumerId) {
        String spId = ApplicationUtils.getWorkingSpId();
        VccUserRseponse vccUser = getVccUser(subsCode,"",null);
        //查询客户信息
        //判断该客户是否存在
        QueryWrapper<Consumer> consumerWrapper = new QueryWrapper<>();
        consumerWrapper.lambda().eq(Consumer::getId, Integer.valueOf(consumerId))
                .eq(Consumer::getSubsCode, subsCode)
                .eq(Consumer::getIsDeleted, Constants.IS_DELETED_FALSE)
                .eq(Consumer::getSpId, spId);
        Consumer consumer = this.getOne(consumerWrapper);
        if (consumer == null) {
            throw new BizException("该客户id,户号对应客户不存在!");
        }
        Boolean flag = true;
        Consumer consumerNew = new Consumer();
        String statusName = CustStatusEnum.getCustStatusName(vccUser.getCustStatus());
        String custType  = queryDictMapByCodeNoSpId(CUST_TYPE_ENUM,CustTypeEnum.toMap()).get(vccUser.getCustType());
        String custTypeCode  = vccUser.getCustType();
        //存在信息更新
        if (!vccUser.getCustName().equals(consumer.getCustName())) {
            flag = false;
            consumerNew.setCustName(vccUser.getCustName());
        }
        if (!vccUser.getCustAddress().equals(consumer.getCustAddress())) {
            flag = false;
            consumerNew.setCustAddress(vccUser.getCustAddress());
        }
        if (!vccUser.getCustPhone().equals(consumer.getCustPhone())) {
            flag = false;
            consumerNew.setCustPhone(vccUser.getCustPhone());
        }
        if (!statusName.equals(consumer.getCustStatus())) {
            flag = false;
            consumerNew.setCustStatus(statusName);
        }
        if (custType.equals(consumer.getCustType())) {
            flag = false;
            consumerNew.setCustType(custType);
        }
        if (custTypeCode.equals(consumer.getCustTypeCode())) {
            flag = false;
            consumerNew.setCustTypeCode(custTypeCode);
        }
        if (!flag) {
            consumerNew.setId(Integer.valueOf(consumerId));
            this.updateById(consumerNew);
            return "户表信息已更新。";
        }
        return "户表信息已是最新";
    }

    @Override
    public PageUtil<CustListResponse> custList(CustListRequest request) {
        String spId = ApplicationUtils.getWorkingSpId();
        //所属组织
        List<String> spIds = organizationService.getSpIds(spId);
        if (!org.springframework.util.StringUtils.isEmpty(request.getSpId())) {
            //如果查询条件不为空，按查询条件来
            spIds.clear();
            spIds.add(request.getSpId());
        }
        //组织名称列表
        List<OrganizationResponse> organizationList = organizationService.getList(ApplicationUtils.getWorkingSpId());

        QueryWrapper<Consumer> queryWrapper = new QueryWrapper<>();
        //判断是否按照行业查询
        if (StringUtil.isNotEmpty(request.getIndustryType())) {
            queryWrapper.lambda().eq(Consumer::getIndustryType, request.getIndustryType());
        }
        if (StringUtil.isNotEmpty(request.getCustInfo())) {
            //按户名/户号查询
            queryWrapper.lambda().and(wrapper -> wrapper.eq(Consumer::getCustName, request.getCustInfo())
                    .or().eq(Consumer::getSubsCode, request.getCustInfo()));
        }
        queryWrapper.lambda().eq(Consumer::getIsDeleted, Constants.IS_DELETED_FALSE)
                .in(Consumer::getSpId, spIds)
                .orderByDesc(Consumer::getUpdatedAt);

        Page<Object> page = PageHelper.startPage(request.getPage(), request.getPageSize());
        List<Consumer> consumerList = consumerMapper.selectList(queryWrapper);
        List<CustListResponse> responses = BeanConvertUtils.convertListTo(consumerList, CustListResponse::new);
        List<DictionaryItemRespDTO> industryType = holder.getIndustryTypeZJ();

        //查询组织架构名称
        List<CompanyResponse> companyNameList = companyService.queryCompanyNameList(spIds);
        Map<String, String> companyResponseMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(companyNameList)) {
            companyResponseMap = companyNameList.stream().collect(Collectors.toMap(CompanyResponse::getSpId, CompanyResponse::getName, (key1, key2) -> key2));
        }
        //批量查询字典
        List<DictionaryItemRespDTO> orgMapSubsCodeList = holder.getDictionaryByKey(ORG_MAP_SUBSCODE);
        Map<String, String> orgSubsCodeMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(orgMapSubsCodeList)) {
            orgSubsCodeMap = orgMapSubsCodeList.stream().collect(Collectors.toMap(DictionaryItemRespDTO::getDescription, DictionaryItemRespDTO::getCompanyName));
        }
        for (CustListResponse response : responses) {
            response.setStatusAnybroken(false);
            response.setStatusAnyalert(false);
            response.setStatusAnyoffline(false);
            response.setStatusAnynormal(true);

            if (StringUtils.isNotEmpty(response.getOrgCode()) && orgSubsCodeMap.containsKey(response.getOrgCode())) {
                response.setCompanyName(orgSubsCodeMap.get(response.getOrgCode()));
            } else {
                if (companyResponseMap.containsKey(response.getSpId())) {
                    response.setCompanyName(companyResponseMap.get(response.getSpId()));
                }
            }
            for (DictionaryItemRespDTO dto : industryType) {
                if (dto.getValue().equals(response.getIndustryType())) {
                    response.setIndustryTypeName(dto.getName());
                }
            }
            //所属组织
            if (!CollectionUtils.isEmpty(organizationList)) {
                List<OrganizationResponse> collect = organizationList.stream()
                        .filter(a -> a.getSpId().equals(response.getSpId())).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(collect)) {
                    response.setSpName(collect.get(0).getSpName());
                }
            }

        }
        //获取各个用户的 设备状态
        List<Integer> consumerIds = consumerList.stream().map(Consumer::getId).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(consumerIds)) {
            QueryWrapper<Dtu> dtuQueryWrapper = new QueryWrapper<>();
            dtuQueryWrapper.lambda().in(Dtu::getConsumerId, consumerIds)
                    .eq(Dtu::getIsDeleted, Constants.IS_DELETED_FALSE)
                    .in(Dtu::getSpId, spIds);
            List<Dtu> dtuList = dtuMapper.selectList(dtuQueryWrapper);
            for (Dtu dtu : dtuList) {
                LatestLog latestLog = latestLogService.get(dtu.getIMEI(), dtu.getSpId());
                //设备状态 0:离线 1:正常 2:低报 3:高报 4:故障
                if (latestLog.getEquipmentStatus().equals(0)) {
                    for (CustListResponse response : responses) {
                        if (response.getId().equals(dtu.getConsumerId())) {
                            response.setStatusAnyoffline(true);
                            //统计该客户的离线设备数
                            response.setOfflineSum(response.getOfflineSum() + 1);
                        }
                    }
                } else if (latestLog.getEquipmentStatus().equals(2) || latestLog.getEquipmentStatus().equals(3) || latestLog.getEquipmentStatus().equals(6)) {
                    for (CustListResponse response : responses) {
                        if (response.getId().equals(dtu.getConsumerId())) response.setStatusAnyalert(true);
                    }
                } else if (latestLog.getEquipmentStatus().equals(4)) {
                    for (CustListResponse response : responses) {
                        if (response.getId().equals(dtu.getConsumerId())) response.setStatusAnybroken(true);
                    }
                }
            }
            //当设备都离线时,改变状态
            for (Integer consumerId : consumerIds) {
                //获取客户的设备总数
                int size = dtuList.stream().filter(d -> d.getConsumerId().equals(consumerId))
                        .collect(Collectors.toList()).size();
                CustListResponse response = responses.stream().filter(r -> r.getId().equals(consumerId))
                        .collect(Collectors.toList()).get(0);
                if (response.getOfflineSum().equals(size)) {
                    response.setStatusAnynormal(false);
                }
            }
        }

        if (CollectionUtil.isNotEmpty(responses)){
            responses.forEach(response -> {
                response.setConsumerId(response.getId());
                if (response.getConsumerType().equals(CONSUMER_TYPE_ZJ)) {
                    response.setIdStr(CONSUMER_ID_ZJ + response.getId());
                } else {
                    response.setIdStr(response.getId() + "");
                }
            });
        }
        commonService.loadFieldAndPackaging(responses, CustListResponse.class,
                responses.stream().map(CustListResponse::getConsumerId).collect(Collectors.toList()), null, null, spId,PageListCode.CUSTOMER_LIST.getCode());
        PageUtil<CustListResponse> pageUtil = new PageUtil<>();
        pageUtil.setPage(request.getPage());
        pageUtil.setPageSize(request.getPageSize());
        pageUtil.setTotal(page.getTotal());
        pageUtil.setList(responses);

        return pageUtil;
    }

    @Override
    public PageUtil<CustListResponse> custListAsst(CustListRequest request) {
        String spId = ApplicationUtils.getWorkingSpId();
        //所属组织
        List<String> spIds = organizationService.getSpIds(spId);
        if (!org.springframework.util.StringUtils.isEmpty(request.getSpId())) {
            //如果查询条件不为空，按查询条件来
            spIds.clear();
            spIds.add(request.getSpId());
        }
        //组织列表
        List<OrganizationResponse> organizationList = organizationService.getList(ApplicationUtils.getWorkingSpId());

        //查询 客户表中用户id 且在 bindingOrder中对工单号进行去重
        Page<Object> page = PageHelper.startPage(request.getPage(), request.getPageSize());
        List<CustListAsstVO> voList = consumerMapper.custlistAsst(spIds, request.getIndustryType(), request.getContactInfo());
        List<CustListResponse> custListResponses = BeanConvertUtils.convertListTo(voList, CustListResponse::new);

        //查询紫荆用户
        QueryWrapper<Consumer> consumerQueryWrapper = new QueryWrapper<>();
        consumerQueryWrapper.lambda().eq(Consumer::getIsDeleted, IS_DELETED_FALSE)
                .eq(Consumer::getConsumerType, CONSUMER_TYPE_ZJ)
                .in(Consumer::getSpId, spIds);
        if (StringUtil.isNotEmpty(request.getCustomerAddress())) {
            consumerQueryWrapper.lambda().like(Consumer::getCustomerAddress, request.getCustomerAddress());
        }
        List<Consumer> zjConsumerList = this.list(consumerQueryWrapper);
        List<CustListResponse> zjCustListResponses = BeanConvertUtils.convertListTo(zjConsumerList, CustListResponse::new);
        //进行客户信息合并
        custListResponses.addAll(zjCustListResponses);

        //查询组织架构名称
        List<CompanyResponse> companyNameList = companyService.queryCompanyNameList(spIds);
        Map<String, String> companyResponseMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(companyNameList)) {
            companyResponseMap = companyNameList.stream().collect(Collectors.toMap(CompanyResponse::getSpId, CompanyResponse::getName, (key1, key2) -> key2));
        }
        //批量查询字典
        List<DictionaryItemRespDTO> orgMapSubsCodeList = holder.getDictionaryByKey(ORG_MAP_SUBSCODE);
        Map<String, String> orgSubsCodeMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(orgMapSubsCodeList)) {
            orgSubsCodeMap = orgMapSubsCodeList.stream().collect(Collectors.toMap(DictionaryItemRespDTO::getDescription, DictionaryItemRespDTO::getCompanyName));
        }
        //对结果赋默认值
        for (CustListResponse response : custListResponses) {
            response.setStatusAnybroken(false);
            response.setStatusAnyalert(false);
            response.setStatusAnyoffline(false);
            response.setStatusAnynormal(true);
            if (StringUtils.isNotEmpty(response.getOrgCode()) && orgSubsCodeMap.containsKey(response.getOrgCode())) {
                response.setCompanyName(orgSubsCodeMap.get(response.getOrgCode()));
            } else {
                if (companyResponseMap.containsKey(response.getSpId())) {
                    response.setCompanyName(companyResponseMap.get(response.getSpId()));
                }
            }

            //所属组织
            if (!CollectionUtils.isEmpty(organizationList)) {
                List<OrganizationResponse> collect = organizationList.stream()
                        .filter(a -> a.getSpId().equals(response.getSpId())).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(collect)) {
                    response.setSpName(collect.get(0).getSpName());
                }
            }
        }
        //查询紫荆客户绑定的设备状态
        List<Integer> consumerIds = zjConsumerList.stream().map(Consumer::getId).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(consumerIds)) {
            QueryWrapper<Dtu> dtuQueryWrapper = new QueryWrapper<>();
            dtuQueryWrapper.lambda().in(Dtu::getConsumerId, consumerIds)
                    .eq(Dtu::getIsDeleted, Constants.IS_DELETED_FALSE)
                    .eq(Dtu::getSpId, spId);
            List<Dtu> dtuList = dtuMapper.selectList(dtuQueryWrapper);
            for (Dtu dtu : dtuList) {
                LatestLog latestLog = latestLogService.get(dtu.getIMEI(), dtu.getSpId());
                //设备状态 0:离线 1:正常 2:低报 3:高报 4:故障 6报警
                if (latestLog.getEquipmentStatus().equals(0)) {
                    for (CustListResponse response : custListResponses) {
                        if (response.getId().equals(dtu.getConsumerId())) {
                            response.setStatusAnyoffline(true);
                            //统计该客户的离线设备数
                            response.setOfflineSum(response.getOfflineSum() + 1);
                        }
                    }
                } else if (latestLog.getEquipmentStatus().equals(2) || latestLog.getEquipmentStatus().equals(3)) {
                    for (CustListResponse response : custListResponses) {
                        if (response.getId().equals(dtu.getConsumerId())) response.setStatusAnyalert(true);
                    }
                } else if (latestLog.getEquipmentStatus().equals(4)) {
                    for (CustListResponse response : custListResponses) {
                        if (response.getId().equals(dtu.getConsumerId())) response.setStatusAnybroken(true);
                    }
                } else if (latestLog.getEquipmentStatus().equals(6)) {
                    for (CustListResponse response : custListResponses) {
                        if (response.getId().equals(dtu.getConsumerId())) response.setStatusAnyalert(true);
                    }
                }
            }
            //当设备都离线时,改变状态
            for (Integer consumerId : consumerIds) {
                //获取客户的设备总数
                int size = dtuList.stream().filter(d -> d.getConsumerId().equals(consumerId))
                        .collect(Collectors.toList()).size();
                CustListResponse response = custListResponses.stream().filter(r -> r.getId().equals(consumerId))
                        .collect(Collectors.toList()).get(0);
                if (response.getOfflineSum().equals(size)) {
                    response.setStatusAnynormal(false);
                }
            }
        }


        // 时刻助手销售单设备状态
        List<String> orderNoList = voList.stream().map(CustListAsstVO::getOrderNo).collect(Collectors.toList());
        //根据工单号获得该工单下的所有设备号,及其状态
        List<DtuBindingOrder> orderList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(orderNoList)) {
            QueryWrapper<DtuBindingOrder> orderQueryWrapper = new QueryWrapper<>();
            orderQueryWrapper.lambda().in(DtuBindingOrder::getOrderNo, orderNoList)
                    .eq(DtuBindingOrder::getIsDeleted, IS_DELETED_FALSE)
                    .eq(DtuBindingOrder::getSpId, spId);
            orderList = dtuBindingOrderMapper.selectList(orderQueryWrapper);
        }
        for (DtuBindingOrder order : orderList) {
            LatestLog latestLog = latestLogService.get(order.getDeviceId(), spId);
            //设备状态 0:离线 1:正常 2:低报 3:高报 4:故障
            if (latestLog.getEquipmentStatus().equals(0)) {
                for (CustListResponse response : custListResponses) {
                    if (response.getOrderNo() != null && order.getOrderNo() != null &&
                            response.getOrderNo().equals(order.getOrderNo())) {
                        response.setStatusAnyoffline(true);
                        //统计该客户的离线设备数
                        response.setOfflineSum(response.getOfflineSum() + 1);
                    }
                }
            } else if (latestLog.getEquipmentStatus().equals(2) || latestLog.getEquipmentStatus().equals(3)) {
                for (CustListResponse response : custListResponses) {
                    if (response.getOrderNo().equals(order.getOrderNo())) response.setStatusAnyalert(true);
                }
            } else if (latestLog.getEquipmentStatus().equals(4)) {
                for (CustListResponse response : custListResponses) {
                    if (response.getOrderNo().equals(order.getOrderNo())) response.setStatusAnybroken(true);
                }
            }
        }
        List<Integer> consumerIdList = custListResponses.stream().map(CustListResponse::getId).collect(Collectors.toList());
        //当设备都离线时,改变状态
        for (Integer consumerId : consumerIdList) {
            //获取客户的设备总数
            int size = orderList.stream().filter(d -> d.getConsumerId().equals(consumerId))
                    .collect(Collectors.toList()).size();
            CustListResponse response = custListResponses.stream().filter(r -> r.getId().equals(consumerId))
                    .collect(Collectors.toList()).get(0);
            if (response.getOfflineSum().equals(size)) {
                response.setStatusAnynormal(false);
            }
        }
        log.info("custListAsst-custListResponses:{}", JSONObject.toJSONString(custListResponses));
        custListResponses.forEach(response -> {
            //idStr
            if (response.getConsumerType() != null &&
                    response.getConsumerType().equals(CONSUMER_TYPE_ZJ)) {
                response.setIdStr(CONSUMER_ID_ZJ + response.getId());
            } else {
                response.setIdStr(response.getId() + "");
            }
        });

        PageUtil<CustListResponse> pageUtil = new PageUtil<>();
        pageUtil.setPage(request.getPage());
        pageUtil.setPageSize(request.getPageSize());
        pageUtil.setTotal(page.getTotal());
        pageUtil.setList(custListResponses);

        return pageUtil;
    }


    /**
     * 获取字典值
     *
     * @param value
     * @param dictCode
     * @return
     */
    @Override
    public String dictionaryname(String value, String dictCode) {
        List<DictionaryItemRespDTO> operator = holder.getDictionaryByKey(dictCode);
        for (DictionaryItemRespDTO dto : operator) {
            if (dto.getValue().equals(value)) {
                return dto.getName();
            }
            ;
        }
        log.info("spId:{}下未查询到 {}-{}对应字典.", ApplicationUtils.getHeaderSpId(), dictCode, value);
        return value;
    }

    @Override
    public ConsumerDetailResponse custDetail(CustDetailRequest request) {
        log.info("CustDetailRequest : {}", JSONObject.toJSONString(request));
        ConsumerDetailResponse response = new ConsumerDetailResponse();
        // 查询 订单基本信息
        QueryWrapper<DtuBindingOrder> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.lambda().eq(DtuBindingOrder::getOrderNo, request.getOrderNo())
                .eq(DtuBindingOrder::getMemberId, request.getMemberId())
                .eq(DtuBindingOrder::getIsDeleted, IS_DELETED_FALSE);
        List<DtuBindingOrder> orderList = dtuBindingOrderMapper.selectList(orderQueryWrapper);
        ConsumerResponse consumerResponse = new ConsumerResponse();
        if (!CollectionUtils.isEmpty(orderList)) {
            DtuBindingOrder order = orderList.get(0);
            consumerResponse.setId(order.getConsumerId());
            consumerResponse.setMemberId(request.getMemberId());
            consumerResponse.setContactsName(order.getCustName());
            consumerResponse.setContactsTelephone(order.getPhone());
            if (StringUtil.isNotEmpty(order.getRealAddress())) {
                consumerResponse.setInstallationAddress(order.getRealAddress());
            } else {
                consumerResponse.setInstallationAddress(order.getAddress());
            }
        }
        response.setConsumerResponse(consumerResponse);
        //获取该工单下的所有设备
        List<ConsumerEquipmentResponse> equipmentVOList = new ArrayList<>();
        List<String> dtuIds = orderList.stream().map(DtuBindingOrder::getDeviceId).collect(Collectors.toList());
        if (dtuIds != null){
            return response;
        }
        List<Dtu> dtuList = equipmentService.listByIds(dtuIds);
        if (CollectionUtil.isNotEmpty(dtuList)) {
            //设备厂商名称
            ConsoleSkSupplierListResponse supplierList = equipmentCmpService.supplierListRequest();
            log.info("调用厨房查询厂商接口返回：{}", supplierList);
            List<AlarmSupplierListVo> supplierListVos = new ArrayList<>();
            if (supplierList != null && supplierList.getCode() == 0 && supplierList.getData() != null && org.apache.commons.collections.CollectionUtils.isNotEmpty(supplierList.getData())) {
                supplierListVos = supplierList.getData();
            }
            for (Dtu dtu : dtuList) {
                ConsumerEquipmentResponse vo = new ConsumerEquipmentResponse();
                BeanUtils.copyProperties(dtu, vo);
                //控制器的点位数
                if (EquipmentType.GAS_ALARM_CONTROLLER.getCode().equals(dtu.getEquipmentType())) {
                    DeviceStateVO deviceStateVO = deviceStateService.getDeviceStateByImei(dtu.getIMEI(), dtu.getSpId());
                    vo.setPoint(deviceStateVO.getDetectorCount());
                }

                //设备类型
                String equipmentType = this.dictionaryname(dtu.getEquipmentType(), "Equipment_type");
                vo.setEquipmentType(equipmentType);
                //String manufacturer = this.dictionaryname(dtu.getEquipmentManufacturer(), "Equipment_manufacturer");
                List<AlarmSupplierListVo> listVos = supplierListVos.stream().filter(a -> a.getAlarmSystemCode().equals(
                        dtu.getEquipmentManufacturer())).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(listVos)) {
                    vo.setEquipmentManufacturer(listVos.get(0).getMsName());
                }
                String operator = this.dictionaryname(dtu.getOperators(), "Operator");
                vo.setOperators(operator);
                LatestLog latestLog = latestLogService.get(dtu.getIMEI(), dtu.getSpId());
                if (latestLog == null) {
                    vo.setEquipmentStatus(null);  // 状态
                    vo.setEquipmentStatusInfo(null);  //状态信息
                    vo.setLatestTime(null);          // 最近上报时间
                    equipmentVOList.add(vo);
                    continue;
                }
                log.info("latestLog : {}", latestLog.toString());
                //判断设备类型,赋值
                vo.setEquipmentStatus(latestLog.getEquipmentStatus());  // 状态
                vo.setEquipmentStatusInfo(latestLog.getEquipmentStatusInfo());  //状态信息
                vo.setLatestTime(latestLog.getLatestTime());
                equipmentVOList.add(vo);
            }
            log.info("detail: 设备信息:{}", equipmentVOList.toString());
        }
        return response;
    }

    @Override
    public String batchImportWorkOrderSync(MultipartFile file) {
        String spId = ApplicationUtils.getWorkingSpId();
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            throw new BizException("获取文件流失败");
        }
        log.info("importData-timeStart:{}", System.currentTimeMillis());
        String uuid = IdUtil.fastSimpleUUID();
        ExcelReader reader = ExcelUtil.getReader(inputStream, 0); //指定输入流和sheet
        List<List<Object>> read = reader.read(1, reader.getRowCount(),false);
        String username = ApplicationUtils.getWorkingUser().getUsername();
        String applicationName = ApplicationUtils.getWorkingUser().getName();
        FileUpload fileUpload = new FileUpload();
        fileUpload = new FileUpload();
        fileUpload.setFileName(file.getOriginalFilename());
        fileUpload.setRowCount(read.size());
        fileUpload.setUploadTime(new Date());
        fileUpload.setUploadCreator(username);
        fileUpload.setCreatorName(applicationName);
        fileUpload.setUploadCode("UPLOAD0003");
        fileUpload.setSpId(spId);
        fileUpload.setUploadStatus("waiting");
        //上传文件路径
        String url = fileUtil.uploadFile(file.getOriginalFilename(), file);
        log.info(uuid + " importData-url:{}", JSONObject.toJSONString(url));
        fileUpload.setUploadUrl(url);
        fileUploadMapper.insert(fileUpload);
        log.info(uuid + " importData-fileUpload:{}", JSONObject.toJSONString(fileUpload));
        Integer id = fileUpload.getId();
        // 从主线程获取用户数据 放到局部变量中
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        SecurityContext context = SecurityContextHolder.getContext();
        executor.submit(() -> {
            // 把旧RequestAttributes放到新线程的RequestContextHolder中
            RequestContextHolder.setRequestAttributes(attributes);
            SecurityContextHolder.setContext(context);
            ImportWorkOrder(file, spId, read, username, applicationName, id, uuid);
        });
        LogVO vo = new LogVO();
        vo.setResultCode(Constants.OPERATE_RESULT_SUCCESS);
        LogRecordAspect.threadLocal.set(vo);
        log.info(uuid + " importData-return: {}", System.currentTimeMillis());
        return "";
    }

    private Integer ImportWorkOrder(MultipartFile file, String spId, List<List<Object>> read, String username, String applicationName, Integer id, String uuid) {
        //错误信息集合, key为行号, list为该行出现的错误
        HashMap<String, String> errorMap = new HashMap<>();
        log.info(uuid + " importDtu-start......");
        List<String> codeList = new ArrayList<>();
        List<String> imeiAllList = new ArrayList<>();
        List<Object> consumer = new ArrayList<>(); // 存储错误的导入客户，用于判断导入状态
        List<Integer> errors = new ArrayList<>(); // 存储错误行号；
        log.info(uuid + " importData-data:{}", JSONObject.toJSONString(read));

        for (int i = 0; i < read.size(); i++) {
            log.info("开始校验行号:{} , 数据:{}", i + 2, read.get(i).toString());
            //校验信息汇总
            List<String> errorList = new ArrayList<>();
            List<Object> objects = read.get(i);
            //长度不足
            if (objects.size() < 31) {
                errorList.add(ConsumerUploadConst.DATE_NULL);
                log.info("行号:{}校验完毕, 错误信息:{}", i + 2, JSON.toJSONString(errorList));
                errorMap.put(Integer.toString(i + 2), errorList.toString());
                consumer.add(read.get(i));
                errors.add(i + 2);
                continue;
            }
            String subsCode = objects.get(0) + "";
            String name = objects.get(1) + "";
            String industryType = objects.get(2) + "";
            String isbuy = objects.get(3) + "";
            String buyaddr = objects.get(4) + "";
            //设备imei
            ArrayList<String> imeiList = new ArrayList<>();
            for (int j = 5; j <= 14; j += 2) {
                String IMEI = objects.get(j) + "";
                log.info("IMEI校验 :{}", IMEI);
                if (isNotNull(IMEI)) {
                    //设备imei号存在时, 校验安装位置存在
                    imeiList.add(IMEI);
                    if (isNull(objects.get(j + 1) + "")) {
                        errorList.add(ConsumerUploadConst.INSTALLATION_POSITION_NULL);
                    }
                }
            }
            log.info("imeiList校验 :{}", imeiList);
            //校验户号, 存在且未绑定
            if (!"null".equals(subsCode) && StringUtil.isNotEmpty(subsCode)) {
                List<String> subsCodeError = checkSubsCodeC(subsCode, spId);
                errorList.addAll(subsCodeError);
            } else {
                errorList.add(ConsumerUploadConst.SUBS_NULL);
            }
            //检验 客户名格式
            if (!"null".equals(name) && StringUtil.isNotEmpty(name) && !name.matches("^(?!_)(?!.*?_$)[a-zA-Z0-9_\\u4e00-\\u9fa5]{2,32}$")) {
                errorList.add(ConsumerUploadConst.NAME_ILLEGAL);
            }
            //行业类型不为空,且在字典中
            List<String> industryTypeError = checkType(industryType,spId);;
            errorList.addAll(industryTypeError);
            //校验 是否内购产品
            if (!"null".equals(isbuy) && StringUtil.isNotEmpty(isbuy)) {
                if (!MbpConst.TRUE.equals(isbuy) && !MbpConst.FALSE.equals(isbuy)) {
                    errorList.add(ConsumerUploadConst.ISBUY_ERROR);
                }
            } else {
                errorList.add(ConsumerUploadConst.ISBUY_NULL);
            }
            //校验 购买地点
            if (!"null".equals(buyaddr) && StringUtil.isNotEmpty(buyaddr)) {
                if (!MbpConst.ADDR_IN.equals(buyaddr) && !MbpConst.ADDR_OUT.equals(buyaddr)) {
                    errorList.add(ConsumerUploadConst.BUYADDR_ERROR);
                }
            } else {
                errorList.add(ConsumerUploadConst.BUYADDR_NULL);
            }

            //如果有imei,就校验imei号,不为空,未绑定, 存在
            if (!imeiList.isEmpty()) {
                List<String> imeiError = checkIMEI(imeiList, spId);
                errorList.addAll(imeiError);
            }
            //联系人
            ArrayList<String> telList = new ArrayList<>();
            List<String> contactError = new ArrayList<>();
            for (int a = 15; a <= 29; a = a + 3) {
                String contactName = objects.get(a) + "";
                String tel = objects.get(a + 1) + "";
                String level = objects.get(a + 2) + "";
                if (!"null".equals(tel) && StringUtil.isNotEmpty(tel)) {
                    telList.add(tel);
                }
                //校验 联系人字段, 三个字段同事存在或不存在, 手机号格式, 级别
                contactError.addAll(checkContact(contactName, tel, level));
            }
            //联系人电话不重复
            boolean isRepeat = telList.size() != new HashSet<>(telList).size();
            if (isRepeat) {
                contactError.add(ConsumerUploadConst.CONTACT_TELEPHONE_REPEAT);
            }
            errorList.addAll(contactError);
            //对错误信息去重
            if (CollectionUtil.isNotEmpty(errorList)) {
                consumer.add(read.get(i));
                errors.add(i + 2);
                errorMap.put(Integer.toString(i + 2), errorList.stream().distinct().collect(Collectors.toList()).toString());
            }
            log.info("行号:{}校验完毕, 错误信息:{}", i + 2, JSON.toJSONString(errorList));
            if (isNotNull(subsCode)) {
                codeList.add(subsCode);
            }
            imeiAllList.addAll(imeiList);

        }
        //表中户号不重复,  设备号不重复
        ArrayList<String> infoErrorList = new ArrayList<>();
        if (codeList.size() != new HashSet<>(codeList).size()) {
            infoErrorList.add(ConsumerUploadConst.SUBS_REPEAT);
        }
        if (imeiAllList.size() != new HashSet<>(imeiAllList).size()) {
            infoErrorList.add(ConsumerUploadConst.IMEI_REPEAT);
        }
        if (CollectionUtil.isNotEmpty(infoErrorList)) {
            errorMap.put("info", infoErrorList.toString());
        }

        //校验全部通过
        //新增导入记录
        FileUpload fileUpload = new FileUpload();
        fileUpload.setFileName(file.getOriginalFilename());
        fileUpload.setRowCount(read.size());
        fileUpload.setUploadTime(new Date());
        fileUpload.setUploadCreator(username);
        fileUpload.setCreatorName(applicationName);
        fileUpload.setSpId(spId);
        fileUpload.setId(id);
        fileUpload.setUploadCode("UPLOAD0003");
        log.info("importData-fileUpload-pre:{}", JSONObject.toJSONString(fileUpload));
        //上传文件路径
        String url = fileUtil.uploadFile(file.getOriginalFilename(), file);
        log.info("importData-url:{}", JSONObject.toJSONString(url));
        fileUpload.setUploadUrl(url);
        // 存储错误信息
        List<Map<String, String>> jsonList = new ArrayList<>();
        log.info("importData-errors:{}", JSONObject.toJSONString(errors));
        try {
            if (!CollectionUtil.isEmpty(errors)) {
                errorMap.forEach((integer, s) -> {
                    Map<String, String> res = new HashMap<>();
                    res.put("number", integer);
                    res.put("reason", s);
                    jsonList.add(res);
                });
            }
            fileUpload.setJsonInfo(JSONObject.toJSONString(jsonList));
            log.info("importData-fileUploadMapper:{}", JSONObject.toJSONString(errors));
        } catch (Exception e) {
            log.info("insert-error:{}", e);
        }


        log.info("客户导入校验全部完成");
        StringBuilder sb = new StringBuilder();
        Integer resultCode = 1;
        //企业操作记录
        LogVO vo = new LogVO();
        if (CollectionUtil.isEmpty(errorMap) && CollectionUtil.isEmpty(consumer)) {
            for (int i = 0; i < read.size(); i++) {
                //发起
                Integer consumerId = mbpWorkOrderService.batchInitiateByExcel(read.get(i),spId);
                sb.append("客户ID:").append(consumerId);
                if (i != read.size() - 1) {
                    sb.append("\n");
                }
            }
            fileUpload.setUploadStatus("success");
            fileUploadMapper.updateById(fileUpload);
            vo.setCommonInfo(sb.toString());
        } else if (consumer.size() < read.size()) {
            for (int i = 0; i < read.size(); i++) {
                if (!errors.contains(i + 2)) {
                    //发起
                    Integer consumerId = mbpWorkOrderService.batchInitiateByExcel(read.get(i),spId);
                    sb.append("客户ID:").append(consumerId);
                    if (i != read.size() - 1) {
                        sb.append("\n");
                    }
                }
            }
            resultCode = OPERATE_RESULT_SUCCESS_PART;
            fileUpload.setUploadStatus("part_success");
            fileUploadMapper.updateById(fileUpload);
            sb.append("批量安装导入部分成功");
            vo.setResultCode(OPERATE_RESULT_SUCCESS_PART);
        } else {
            resultCode = OPERATE_RESULT_FAIL;
            fileUpload.setUploadStatus("fail");
            fileUploadMapper.updateById(fileUpload);
            sb.append("批量安装导入");
            vo.setCommonInfo(sb.toString());
            vo.setResultCode(OPERATE_RESULT_FAIL);
        }

        //操作日志log
        OperationLogVO logVO = new OperationLogVO();
        LogRecordAspect.threadLocal.set(vo);
        List<Integer> logCodeList = new ArrayList<>();
        logCodeList.add(OperationTypeEnum.OPERATION_TYPE_4.getCode());
        logVO.setCodeList(logCodeList);
        logVO.setTableName(TableConst.consumer.name());
        operationLogService.insertLog(logVO);

        return resultCode;
    }

    @Override
    public HashMap<String, List<String>> batchImportWorkOrder(MultipartFile file) {
        String spId = ApplicationUtils.getWorkingSpId();
        //错误信息集合, key为行号, list为该行出现的错误
        HashMap<String, List<String>> errorMap = new HashMap<>();
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            throw new BizException("获取文件流失败");
        }
        //获得表头,  所有数据ExcelUtil.getReader("d:/aaa.xlsx");
        ExcelReader reader = ExcelUtil.getReader(inputStream, 0);
        List<List<Object>> read = reader.read(1, reader.getRowCount(), false);
        List<String> codeList = new ArrayList<>();
        List<String> imeiAllList = new ArrayList<>();

        FieldTemplate fieldTemplate = fieldTemplateMapper.getTypeBySpId(spId);
        Map<String,FuncArea> funcAreaMap = null;
        if( FUNC_AREA_ALLOCAT_CUSTOM.equals(fieldTemplate.getFuncAreaAllocat()) ){
            funcAreaMap = functionAreaService.getFuncAreaMapByName();
        }
        //行号 = 索引+1
        List<Object> errorInfo = new ArrayList<>();
        for (int i = 0; i < read.size(); i++) {
            log.info("开始校验行号:{} , 数据:{}", i + 2, read.get(i).toString());
            //校验信息汇总
            List<String> errorList = new ArrayList<>();
            List<Object> objects = read.get(i);
            try {
                //长度不足
                if (objects.size() < 34) {
                    errorList.add(ConsumerUploadConst.DATE_NULL);
                    log.info("行号:{}校验完毕, 错误信息:{}", i + 2, JSON.toJSONString(errorList));
                    errorMap.put(Integer.toString(i + 2), errorList);
                    continue;
                }
                String subsCode = (objects.get(0) + "").trim();
                String name = (objects.get(1) + "").trim();
                String funAreaName = objects.get(2)==null?"":objects.get(2).toString().trim();
                if(!checkFunAreaField(funAreaName,funcAreaMap,"")){
                    errorList.add(ConsumerUploadConst.FUNC_AREA_ERROR);
                }
                String StreetName = objects.get(3)==null?"":objects.get(3).toString().trim();
                if(!checkFunAreaField(StreetName,funcAreaMap,funAreaName)){
                    errorList.add(ConsumerUploadConst.FUNC_STREET_ERROR);
                }
                String tradeAreaName = objects.get(4)==null?"":objects.get(4).toString().trim();
                if(!checkFunAreaField(tradeAreaName,funcAreaMap,"")){
                    errorList.add(ConsumerUploadConst.FUNC_TRADE_AREA_ERROR);
                }
                String industryType = (objects.get(5) + "").trim();
                String isbuy = (objects.get(6) + "").trim();
                String buyaddr = (objects.get(7) + "").trim();
                //设备imei
                ArrayList<String> imeiList = new ArrayList<>();
                for (int j = 8; j <= 17; j += 2) {
                    String IMEI = (objects.get(j) + "").trim();
                    log.info("IMEI校验 :{}", IMEI);
                    if (isNotNull(IMEI)) {
                        //设备imei号存在时, 校验安装位置存在
                        imeiList.add(IMEI);
                        if (isNull(objects.get(j + 1) + "")) {
                            errorList.add(ConsumerUploadConst.INSTALLATION_POSITION_NULL);
                        }
                    }
                }
                log.info("imeiList校验 :{}", imeiList);
                //校验户号, 存在且未绑定
                if (!"null".equals(subsCode) && StringUtil.isNotEmpty(subsCode)) {
                    List<String> subsCodeError = checkSubsCode(subsCode, spId);
                    errorList.addAll(subsCodeError);
                } else {
                    errorList.add(ConsumerUploadConst.SUBS_NULL);
                }
                //检验 客户名格式
                if (!"null".equals(name) && StringUtil.isNotEmpty(name) && !name.matches("^(?!_)(?!.*?_$)[a-zA-Z0-9_\\u4e00-\\u9fa5]{2,32}$")) {
                    errorList.add(ConsumerUploadConst.NAME_ILLEGAL);
                }
                //行业类型不为空,且在字典中
                List<String> industryTypeError = checkType(industryType);
                errorList.addAll(industryTypeError);
                //校验 是否内购产品
                if (!"null".equals(isbuy) && StringUtil.isNotEmpty(isbuy)) {
                    if (!MbpConst.TRUE.equals(isbuy) && !MbpConst.FALSE.equals(isbuy)) {
                        errorList.add(ConsumerUploadConst.ISBUY_ERROR);
                    }
                } else {
                    errorList.add(ConsumerUploadConst.ISBUY_NULL);
                }
                //校验 购买地点
                if (!"null".equals(buyaddr) && StringUtil.isNotEmpty(buyaddr)) {
                    if (!MbpConst.ADDR_IN.equals(buyaddr) && !MbpConst.ADDR_OUT.equals(buyaddr)) {
                        errorList.add(ConsumerUploadConst.BUYADDR_ERROR);
                    }
                } else {
                    errorList.add(ConsumerUploadConst.BUYADDR_NULL);
                }

                //如果有imei,就校验imei号,不为空,未绑定, 存在
                if (!imeiList.isEmpty()) {
                    List<String> imeiError = checkIMEI(imeiList, spId);
                    errorList.addAll(imeiError);
                }
                //联系人
                ArrayList<String> telList = new ArrayList<>();
                List<String> contactError = new ArrayList<>();
                for (int a = 18; a <= 32; a = a + 3) {
                    String contactName = (objects.get(a) + "").trim();
                    String tel = (objects.get(a + 1) + "").trim();
                    String level = (objects.get(a + 2) + "").trim();
                    if (!"null".equals(tel) && StringUtil.isNotEmpty(tel)) {
                        telList.add(tel);
                    }
                    //校验 联系人字段, 三个字段同事存在或不存在, 手机号格式, 级别
                    contactError.addAll(checkContact(contactName, tel, level));
                }
                //联系人电话不重复
                boolean isRepeat = telList.size() != new HashSet<>(telList).size();
                if (isRepeat) {
                    contactError.add(ConsumerUploadConst.CONTACT_TELEPHONE_REPEAT);
                }
                errorList.addAll(contactError);
                if (isNotNull(subsCode)) {
                    codeList.add(subsCode);
                }
                imeiAllList.addAll(imeiList);
            } catch (Exception e) {
                log.error("importData-error:{}",e);
                errorList.add("校验失败");
            }
            //对错误信息去重
            if (CollectionUtil.isNotEmpty(errorList)) {
                errorMap.put(Integer.toString(i + 2), errorList.stream().distinct().collect(Collectors.toList()));
            }
            log.info("行号:{}校验完毕, 错误信息:{}", i + 2, JSON.toJSONString(errorList));

        }
        //表中户号不重复,  设备号不重复
        ArrayList<String> infoErrorList = new ArrayList<>();
        if (codeList.size() != new HashSet<>(codeList).size()) {
            infoErrorList.add(ConsumerUploadConst.SUBS_REPEAT);
        }
        if (imeiAllList.size() != new HashSet<>(imeiAllList).size()) {
            infoErrorList.add(ConsumerUploadConst.IMEI_REPEAT);
        }
        if (CollectionUtil.isNotEmpty(infoErrorList)) {
            errorMap.put("info", infoErrorList);
        }

        //校验全部通过
        //新增导入记录
        FileUpload fileUpload = new FileUpload();
        fileUpload.setFileName(file.getOriginalFilename());
        fileUpload.setRowCount(read.size());
        fileUpload.setUploadTime(new Date());
        fileUpload.setUploadCreator(ApplicationUtils.getWorkingUser().getUsername());
        fileUpload.setCreatorName(ApplicationUtils.getWorkingUser().getName());
        fileUpload.setUploadCode(UploadCodeEnum.EXPORT_3.getCode());
        fileUpload.setUploadUrl(fileUtil.uploadFile(file.getOriginalFilename(), file));
        fileUpload.setSpId(spId);


        log.info("客户导入校验全部完成");
        StringBuilder sb = new StringBuilder();
        if (CollectionUtil.isEmpty(errorMap)) {
            for (int i = 0; i < read.size(); i++) {
                //发起
                Integer consumerId = mbpWorkOrderService.batchInitiateByExcel(read.get(i), funcAreaMap);
                sb.append("客户ID:").append(consumerId);
                if (i != read.size() -1){
                    sb.append("\n");
                }
            }
            fileUpload.setUploadStatus("success");
            fileUploadMapper.insert(fileUpload);

            //操作日志log
            OperationLogVO logVO = new OperationLogVO();
            List<Integer> logCodeList = new ArrayList<>();
            logCodeList.add(OperationTypeEnum.OPERATION_TYPE_4.getCode());
            logVO.setCodeList(logCodeList);
            logVO.setTableName(TableConst.consumer.name());
            operationLogService.insertLog(logVO);

            //企业操作记录
            LogVO vo = new LogVO();
            vo.setCommonInfo(sb.toString());
            LogRecordAspect.threadLocal.set(vo);

            return null;
        } else {
            fileUpload.setUploadStatus("fail");
            fileUploadMapper.insert(fileUpload);
            sb.append("批量安装导入");

            //企业操作记录
            LogVO vo = new LogVO();
            vo.setCommonInfo(sb.toString());
            vo.setResultCode(OPERATE_RESULT_FAIL);
            LogRecordAspect.threadLocal.set(vo);

            return errorMap;
        }



    }

    @Override
    public PageUtil<ReceiverValveLogResponse> receiverMeasureLog(EquipmentLogRequest request) {
        String spId = ApplicationUtils.getWorkingSpId();
        List<RecordReceiverValve> list = new ArrayList<>();
        //所属组织
        List<String> spIds = organizationService.getSpIds(spId);
        Dtu equipment = equipmentService.getDeviceByImeiAndSpIds(request.getImei(), spIds);

        //查询近5个月内
        DateTime startTime = DateUtil.parse(request.getStartTime());
        Page<RecordReceiverValve> page = PageHelper.startPage(request.getPage(), request.getPageSize());
        if (StringUtils.isEmpty(request.getStartTime())) {
            log.info("查询RecordReceiverValve");
            LambdaQueryWrapper<RecordReceiverValve> lqw = new LambdaQueryWrapper<>();
            lqw.eq(RecordReceiverValve::getDeviceId, equipment.getIMEI())
                    .eq(RecordReceiverValve::getIsDeleted, IS_DELETED_FALSE)
                    .orderByDesc(RecordReceiverValve::getRecordAt);
            list = recordReceiverValveService.list(lqw);
        } else {
            log.info("查询RecordReceiverValveHistory");
            String month = StringUtils.substring(request.getStartTime(), 5, 7);
            //查询大于5个月
            List<RecordReceiverValveHistory> historyList = receiverValveHistoryService.selectListByDevice(equipment.getIMEI(), month);
            for (RecordReceiverValveHistory recordReceiverValveHistory : historyList) {
                RecordReceiverValve recordReceiverValve = new RecordReceiverValve();
                BeanUtils.copyProperties(recordReceiverValveHistory,recordReceiverValve);
                list.add(recordReceiverValve);
            }
        }
        if (CollectionUtils.isEmpty(list)) {
            return new PageUtil<>(request.getPage(), request.getPageSize(), 0, null);
        }
        List<ReceiverValveLogResponse> resultList = list.stream().map(item -> {
            ReceiverValveLogResponse response = new ReceiverValveLogResponse();
            response.setTime(item.getRecordAt());
            //接收器状态
            if (RECEIVER_STATUS_OFFLINE == item.getReceiverStatus()) {
                response.setReceiverStatus(RECEIVER_STATUS_OFFLINE_INFO);
            } else if (RECEIVER_STATUS_NORMAL == item.getReceiverStatus()) {
                response.setReceiverStatus(RECEIVER_STATUS_NORMAL_INFO);
            }
            //接收器电池状态
            if (VALVE_WORK_STATUS_BROKEN == item.getValveWorkStatus() && item.getBrokenStatus() != null
                    && item.getBrokenStatus().contains(VALVE_BROKEN_STATUS_74.toString())) {
                response.setBatteryStatus(BATTERY_STATUS_BROKEN_INFO);
            } else {
                response.setBatteryStatus(BATTERY_STATUS_NORMAL_INFO);
            }
            //电磁阀 阀门状态
            if (VALVE_STATUS_OPEN == item.getValveStatus()) {
                response.setValveStatus(VALVE_STATUS_OPEN_INFO);
            } else if (VALVE_STATUS_CLOSE == item.getValveStatus()) {
                response.setValveStatus(VALVE_STATUS_CLOSE_INFO);
            }
            //是否故障
            if (VALVE_WORK_STATUS_NORMAL == item.getValveWorkStatus()) {
                response.setBrokenStatus("否");
            } else if (VALVE_WORK_STATUS_BROKEN == item.getValveWorkStatus()) {
                if (!StringUtils.isEmpty(item.getBrokenStatus())) {
                    String[] signals = item.getBrokenStatus().split(";");
                    StringBuilder brokenReason = new StringBuilder();
                    for (int i = 0; i < signals.length; i++) {
                        switch (signals[i]) {
                            case "70":
                                brokenReason.append(VALVE_BROKEN_STATUS_70_INFO);
                                break;
                            case "71":
                                brokenReason.append(VALVE_BROKEN_STATUS_71_INFO);
                                break;
                            case "72":
                                brokenReason.append(VALVE_BROKEN_STATUS_72_INFO);
                                break;
                            case "73":
                                brokenReason.append(VALVE_BROKEN_STATUS_73_INFO);
                                break;
                            case "74":
                                brokenReason.append(VALVE_BROKEN_STATUS_74_INFO);
                                break;
                        }
                        if (i < (signals.length - 1)) {
                            brokenReason.append(";");
                        }
                    }
                    response.setBrokenStatus(brokenReason.toString());
                }
            }
            return response;
        }).collect(Collectors.toList());
        return new PageUtil<>(request.getPage(), request.getPageSize(), page.getTotal(), resultList);
    }

    @Override
    public List<DictionaryItemRespDTO> getIndustryTypeList() {
        String spId = ApplicationUtils.getWorkingSpId();
        List<String> spIds = organizationService.getSpIds(spId);
        List<DictionaryItemRespDTO> industryTypeZJ = holder.getIndustryTypeZJ(spIds);
        return industryTypeZJ;
    }




    /**
     * 导入-校验行业类型
     *
     * @param industryType
     * @return
     */
    public List<String> checkType(String industryType) {
        ArrayList<String> list = new ArrayList<>();
        if ("null".equals(industryType) && StringUtil.isEmpty(industryType)) {
            list.add(ConsumerUploadConst.INDUSTRY_TYPE_NULL);
            return list;
        }
        List<DictionaryItemRespDTO> industryDTO = holder.getDictionaryByKey(Constants.INDUSTRY_TYPE_CODE);
        if (CollectionUtil.isEmpty(industryDTO)) {
            throw new BizException("未查询到行业字典");
        }
        List<DictionaryItemRespDTO> dtos = industryDTO.stream().filter(dto -> dto.getName().equals(industryType)).collect(Collectors.toList());
        if (CollectionUtil.isEmpty(dtos)) {
            list.add(ConsumerUploadConst.INDUSTRY_TYPE_ILLEGAL);
        }
        log.info("行业类型校验错误：{}", list);
        return list;

    }

    public List<String> checkType(String industryType,String spId) {
        ArrayList<String> list = new ArrayList<>();
        if ("null".equals(industryType) || StringUtil.isEmpty(industryType)) {
            list.add(ConsumerUploadConst.INDUSTRY_TYPE_NULL);
            return list;
        }
        List<DictionaryItemRespDTO> industryDTO = holder.getDictionaryByKey(Constants.INDUSTRY_TYPE_CODE,spId);
        log.info("行业字典返回：{}",industryDTO);
        if (CollectionUtil.isEmpty(industryDTO)) {
            list.add(ConsumerUploadConst.INDUSTRY_TYPE_SEARCH_NULL);
            return list;
        }
        log.info("行业字典");
        List<DictionaryItemRespDTO> dtos = industryDTO.stream().filter(dto -> dto.getName().equals(industryType)).collect(Collectors.toList());
        if (CollectionUtil.isEmpty(dtos)) {
            list.add(ConsumerUploadConst.INDUSTRY_TYPE_ILLEGAL);
        }
        log.info("行业类型校验错误：{}", list);
     return list;

    }

    /**
     * 导入-校验imei号
     *
     * @param imeiList
     * @param spId
     * @return
     */
    public List<String> checkIMEI(List<String> imeiList, String spId) {
        ArrayList<String> list = new ArrayList<>();
        //未传imei号
        if (CollectionUtil.isEmpty(imeiList)) {
            list.add(ConsumerUploadConst.IMEI_NULL);
            return list;
        }
        //不存在于设备表
        QueryWrapper<Dtu> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Dtu::getSpId, spId)
                .eq(Dtu::getIsDeleted, Constants.IS_DELETED_FALSE)
                .in(Dtu::getIMEI, imeiList);
        List<Dtu> dtuList = equipmentService.list(queryWrapper);
        if (dtuList.size() != imeiList.size()) {
            list.add(ConsumerUploadConst.IMEI_NO_FOUND);
        }
        //设备是否已绑定,客户id不为0
        queryWrapper.lambda().ne(Dtu::getConsumerId, 0);
        List<Dtu> dtuList1 = equipmentService.list(queryWrapper);
        if (CollectionUtil.isNotEmpty(dtuList1)) {
            list.add(ConsumerUploadConst.IMEI_BOUND);
        }
        return list;
    }

    /**
     * 校验联系人信息 //行号 = 索引+2
     * for (int i = 0; i < read.size(); i++) {
     *
     * @param name
     * @param tel
     * @param level
     * @return
     */
    public List<String> checkContact(String name, String tel, String level) {
        log.info("校验手机号");
        ArrayList<String> list = new ArrayList<>();
        //存在联系人信息时
        if (isNotNull(name) || isNotNull(tel) || isNotNull(level)) {
            //三个字段必须同时存在
            if (isNull(name) || isNull(tel) || isNull(level)) {
                list.add(ConsumerUploadConst.CONTACT_TELEPHONE_NULL);
            } else {
                if (tel.contains("-")) {
                    if (!tel.matches("^\\\\d{3,4}-\\\\d{7,8}$")) {
                        list.add(ConsumerUploadConst.CONTACT_LANDLINE_ERROR);
                    }
                } else {
                    if (tel.length() > 11) {
                        list.add(ConsumerUploadConst.CONTACT_TELEPHONE_ERROR);
                    }
                }

                if (StringUtil.isNotEmpty(level) && !level.matches("^10|[0-9]$")) {
                    list.add(ConsumerUploadConst.CONTACT_LEVEL_ERROR);
                }
                if (name.length() > 15) {
                    list.add(ConsumerUploadConst.CONTACT_NAME_ERROR);
                }
            }
        }
        return list;
    }


    @Async
    @Override
    public void registerCityDevice(String spId, String imei) {
        List<String> imeiList = new ArrayList<>();
        imeiList.add(imei);
        //查询dtu表并关联客户表
        List<Map<String, Object>> deviceInfoList = dtuMapper.getDeviceInfo(imeiList);
        if (CollectionUtil.isEmpty(deviceInfoList)) {
            return;
        }
        Map<String, Object> map = deviceInfoList.get(0);
        log.info("设备:{}开始注册至余杭政府", imei);
        //调用接口,成功则存入本地
        hangZhouService.registerCityDevice(map);


    }

    @Override
    public PageUtil<CustListResponse> custListV2(CustListRequest request) {
        String spId = ApplicationUtils.getWorkingSpId();
        //所属组织
        List<String> spIds = organizationService.getSpIds(spId);
        if (!org.springframework.util.StringUtils.isEmpty(request.getSpId())) {
            //如果查询条件不为空，按查询条件来
            spIds.clear();
            spIds.add(request.getSpId());
        }
        //组织名称列表
        List<OrganizationResponse> organizationList = organizationService.getList(ApplicationUtils.getWorkingSpId());

        QueryWrapper<Consumer> queryWrapper = new QueryWrapper<>();
        //判断是否按照行业查询
        if (StringUtil.isNotEmpty(request.getIndustryType())) {
            queryWrapper.lambda().eq(Consumer::getIndustryType, request.getIndustryType());
        }
        if (StringUtil.isNotEmpty(request.getCustInfo())) {
            //按户名/户号查询/用户id/手机号
            queryWrapper.lambda().and(wrapper -> wrapper.eq(Consumer::getCustName, request.getCustInfo())
                    .or().eq(Consumer::getSubsCode, request.getCustInfo())
                    .or().eq(Consumer::getCustPhone, request.getCustInfo())
                    .or().eq(Consumer::getPhone, request.getCustInfo())
                    .or().eq(Consumer::getMemberId, request.getCustInfo()));
        }
        if (StringUtil.isNotEmpty(request.getOrgCode())) {
            queryWrapper.lambda().eq(Consumer::getOrgCode, request.getOrgCode());
        }
        if (StringUtil.isNotEmpty(request.getCustomerAddress())) {
            queryWrapper.lambda().like(Consumer::getCustomerAddress, request.getCustomerAddress());
        }
        if (!ObjectUtil.isEmpty(request.getConsumerId()) && request.getConsumerId() > 0) {
            queryWrapper.lambda().eq(Consumer::getId, request.getConsumerId());
        }
        queryWrapper.lambda().eq(Consumer::getIsDeleted, Constants.IS_DELETED_FALSE)
                .in(Consumer::getSpId, spIds)
                .orderByDesc(Consumer::getUpdatedAt);

        //数据权限
        UserFuncCodePermissionDTO userPermission = userPermissionService.getUserDepartPermission(spIds);
        if( null!= userPermission.getFuncCodes() && !userPermission.getFuncCodes().isEmpty()){
            queryWrapper.lambda().and(
                    wrapper -> wrapper.and(qw->qw.isNull(Consumer::getDistrictcode).isNull(Consumer::getTowncode).in(Consumer::getCitycode,userPermission.getFuncCodes()))
                    .or(qw->qw.isNull(Consumer::getTowncode).in(Consumer::getDistrictcode,userPermission.getFuncCodes()))
                    .or(qw->qw.in(Consumer::getTowncode,userPermission.getFuncCodes()))
            );
        }

        Page<Object> page = PageHelper.startPage(request.getPage(), request.getPageSize());
        List<Consumer> consumerList = consumerMapper.selectList(queryWrapper);
        List<Integer> consumerIds = consumerList.stream().map(Consumer::getId).collect(Collectors.toList());
        List<CustListResponse> responses = BeanConvertUtils.convertListTo(consumerList, CustListResponse::new);

        List<DictionaryItemRespDTO> industryType = holder.getIndustryTypeZJ();
        Map<String,String> industryTypeMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(industryType)) {
            for (DictionaryItemRespDTO dto : industryType) {
                industryTypeMap.put(dto.getValue(), dto.getName());
            }
        }

        Map<String,String> orgMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(organizationList)) {
            for (OrganizationResponse organizationResponse:organizationList){
                if( orgMap.containsKey(organizationResponse.getSpId()) ){
                    continue;
                }
                orgMap.put(organizationResponse.getSpId(),organizationResponse.getSpName());
            }
        }

        //查询组织架构名称
        List<CompanyResponse> companyNameList = companyService.queryCompanyNameList(spIds);
        Map<String, String> companyResponseMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(companyNameList)) {
            companyResponseMap = companyNameList.stream().collect(Collectors.toMap(CompanyResponse::getSpId, CompanyResponse::getName, (key1, key2) -> key2));
        }
        //批量查询字典
        List<DictionaryItemRespDTO> orgMapSubsCodeList = holder.getDictionaryByKey(ORG_MAP_SUBSCODE);
        Map<String, String> orgSubsCodeMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(orgMapSubsCodeList)) {
            orgSubsCodeMap = orgMapSubsCodeList.stream().collect(Collectors.toMap(DictionaryItemRespDTO::getDescription, DictionaryItemRespDTO::getCompanyName));
        }

        Map<Integer, ConsumerDeviceStatVO> consumerDeviceMap = new HashMap<>();
        if(ObjectUtil.isNotEmpty(responses)){
            consumerDeviceMap = deviceStateService.getConsumerDeviceState(spIds,consumerIds);
        }

        for (CustListResponse response : responses) {
            response.setStatusAnybroken(false);
            response.setStatusAnyalert(false);
            response.setStatusAnyoffline(false);
            response.setStatusAnynormal(true);

            //燃气公司
            if (StringUtils.isNotEmpty(response.getOrgCode()) && orgSubsCodeMap.containsKey(response.getOrgCode())) {
                response.setCompanyName(orgSubsCodeMap.get(response.getOrgCode()));
            } else {
                if (companyResponseMap.containsKey(response.getSpId())) {
                    response.setCompanyName(companyResponseMap.get(response.getSpId()));
                }
            }
            //所属行业
            if (industryTypeMap.containsKey(response.getIndustryType())) {
                response.setIndustryTypeName(industryTypeMap.get(response.getIndustryType()));
            }
            //所属组织
            if(orgMap.containsKey(response.getSpId())){
                response.setSpName(orgMap.get(response.getSpId()));
            }
            //客户设备的状态统计分析
            if(consumerDeviceMap.containsKey(response.getId())){
                ConsumerDeviceStatVO consumerDeviceStatVO = consumerDeviceMap.get(response.getId());
                response.setOfflineSum(consumerDeviceStatVO.getOfflineNum());
                if(consumerDeviceStatVO.getBrokenNum()>0){
                    response.setStatusAnybroken(true);
                }
                if(consumerDeviceStatVO.getAlertNum()>0){
                    response.setStatusAnyalert(true);
                }
                if(consumerDeviceStatVO.getOfflineNum()>0){
                    response.setStatusAnyoffline(true);
                }
                if(consumerDeviceStatVO.getOfflineNum().equals(consumerDeviceStatVO.getDeviceNum())){
                    response.setStatusAnynormal(false);
                }
            }else{
                response.setStatusAnynormal(false);
            }
            response.setConsumerId(response.getId());
            if (response.getConsumerType().equals(CONSUMER_TYPE_ZJ)) {
                response.setIdStr(CONSUMER_ID_ZJ + response.getId());
            } else {
                response.setIdStr(response.getId() + "");
            }
        }
        commonService.loadFieldAndPackaging(responses, CustListResponse.class,
                responses.stream().map(CustListResponse::getConsumerId).collect(Collectors.toList()), null, null, spId,PageListCode.CUSTOMER_LIST.getCode());
        PageUtil<CustListResponse> pageUtil = new PageUtil<>();
        pageUtil.setPage(request.getPage());
        pageUtil.setPageSize(request.getPageSize());
        pageUtil.setTotal(page.getTotal());
        pageUtil.setList(responses);
        return pageUtil;
    }

    @Override
    public List<ConsumerResponse> batchDetail(ConsumerDetailRequest request) {
        List<ConsumerResponse> responseList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(request.getIds())) {
            QueryWrapper<Consumer> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().in(Consumer::getId, request.getIds()).eq(Consumer::getIsDeleted, 0);
            List<Consumer> consumers = consumerMapper.selectList(queryWrapper);
            if (!CollectionUtils.isEmpty(consumers)) {
                for (Consumer consumer : consumers) {
                    ConsumerResponse consumerResponse = new ConsumerResponse();
                    BeanUtils.copyProperties(consumer, consumerResponse);
                    responseList.add(consumerResponse);
                }
            }
        }
        return responseList;
    }

    @Override
    public void unbindEquipmentToTcis(NewAsstUnbindRequest request, String spId) {
        ConsumerunBindingRequest bindingRequest = new ConsumerunBindingRequest();
        bindingRequest.setImei(request.getImei());
        bindingRequest.setOutOrderCode(request.getPkid());
        bindingRequest.setTemplateType(TemplateTypeEnum.TEMPLATE_TYPE_1.getCode());
        bindingRequest.setBindChannel(BIND_CHANNEL_MBP);
        QueryWrapper<Consumer> consumerQueryWrapper = new QueryWrapper<>();
        consumerQueryWrapper.lambda().eq(Consumer::getSubsCode, request.getSubsCode())
                .eq(Consumer::getSpId,spId)
                .eq(Consumer::getIsDeleted, false);
        List<Consumer> consumers = this.list(consumerQueryWrapper);
        if (CollectionUtil.isNotEmpty(consumers) && StringUtils.isNotEmpty(consumers.get(0).getSubsCode())){
            bindingRequest.setConsumerId(consumers.get(0).getId());
            syncUnbindEquipmentToTcis(bindingRequest,consumers.get(0),spId);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void syncConsumer() {
        int pageIndex = 1;
        int  pageSize = 500;
        long total = 0;
        do{
            Page<Consumer> pages = PageHelper.startPage(pageIndex, pageSize);
            QueryWrapper<Consumer> consumerQueryWrapper = new QueryWrapper<>();
            consumerQueryWrapper.lambda().gt(Consumer::getPositionLat, 0)
                    .gt(Consumer::getPositionLon, 0);
            List<Consumer> consumers = this.list(consumerQueryWrapper);
            pageIndex++;
            total = pages.getTotal();
            log.info("客户表高德转百度{},分页{},{}，{}",pageIndex, pages.getPages(), pages.getPageSize(), pages.getTotal());
            if (org.apache.commons.collections.CollectionUtils.isNotEmpty(consumers)) {
                //开始修改坐标
                for (Consumer consumer : consumers) {
                    if (consumer.getPositionLat() != null && consumer.getPositionLon() != null) {
                        List<BaiDuDetailResp> duDetailResps = CoordinatesTransitionUtil.requestGetAK(consumer.getPositionLon() + "," + consumer.getPositionLat(), baiDuMapsKey);
                        if (!CollectionUtils.isEmpty(duDetailResps)) {
                            consumer.setPositionLon(duDetailResps.get(0).getX());
                            consumer.setPositionLat(duDetailResps.get(0).getY());
                        }
                    }
                }
                this.saveOrUpdateBatch(consumers);
            }
            consumers.clear();
        }while(total > (pageIndex - 1) * pageSize);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addressTurnCoordinate(AddressTurnCoordinateReq req) {
        int pageIndex = 1;
        int  pageSize = 500;
        long total = 0;
        do{
            Page<Consumer> pages = PageHelper.startPage(pageIndex, pageSize);
            QueryWrapper<Consumer> consumerQueryWrapper = new QueryWrapper<>();
            consumerQueryWrapper.lambda().eq(Consumer::getSpId, req.getSpId());
            if (CollectionUtil.isNotEmpty(req.getSubsCodes())) {
                consumerQueryWrapper.lambda().in(Consumer::getSubsCode, req.getSubsCodes());
            }
            List<Consumer> consumers = this.list(consumerQueryWrapper);
            pageIndex++;
            total = pages.getTotal();
            log.info("根据地址转坐标和编码{},分页{},{}，{}",pageIndex, pages.getPages(), pages.getPageSize(), pages.getTotal());
            if (org.apache.commons.collections.CollectionUtils.isNotEmpty(consumers)) {
                //开始修改坐标
                for (Consumer consumer : consumers) {
                    if (StringUtils.isNotEmpty(consumer.getCustAddress()) || StringUtils.isNotEmpty(consumer.getCustomerAddress())){
                        //查询客户地址
                        QueryWrapper<ConsumerLocation> queryWrapper = new QueryWrapper<>();
                        queryWrapper.lambda().eq(ConsumerLocation::getSpId, req.getSpId()).eq(ConsumerLocation::getConsumerId, consumer.getId());
                        List<ConsumerLocation> locationList = consumerLocationService.list(queryWrapper);
                        //查询设备
                        QueryWrapper<Dtu> dtuQueryWrapper = new QueryWrapper<>();
                        dtuQueryWrapper.lambda().eq(Dtu::getSpId, req.getSpId()).eq(Dtu::getConsumerId, consumer.getId());
                        List<Dtu> dtuList = equipmentService.list(dtuQueryWrapper);
                        String address = consumer.getCustAddress();
                        if (StringUtils.isNotEmpty(consumer.getCustomerAddress())) {
                            address = consumer.getCustomerAddress();
                        }
                        double[] location = locationUtil.baiDuUrlGeocoding(req.getAddress() + address);
                        //维度
                        double lat = location[0];
                        //经度
                        double lng = location[1];
                        if (lat != 0 && lng != 0) {
                            consumer.setPositionLat(lat);
                            consumer.setPositionLon(lng);
                            JSONObject resultJson = locationUtil.baiDuGeocoding(lat, lng);
                            if ("0".equals(resultJson.getString("status")) &&
                                    null != resultJson.getJSONObject("result") &&
                                    null != resultJson.getJSONObject("result").getJSONObject("addressComponent")) {
                                JSONObject addressComponent = resultJson.getJSONObject("result").getJSONObject("addressComponent");
                                String province = addressComponent.getString("province");
                                String city = addressComponent.getString("city");
                                if (org.apache.commons.lang.StringUtils.isEmpty(city)) {
                                    city = province;
                                }
                                String citycode = consumerLocationService.getCityCodeByCityName(province, city, addressComponent.getIntValue("city_level"));
                                String district = addressComponent.getString("district");
                                String adCode = addressComponent.getString("adcode");
                                String towncode = addressComponent.getString("town_code");
                                String township = addressComponent.getString("town");
                                if( org.apache.commons.lang.StringUtils.isNotEmpty(city) ){
                                    if (CollectionUtil.isNotEmpty(locationList)) {
                                        for (ConsumerLocation consumerLocation : locationList) {
                                            consumerLocation.setCity(city);
                                        }
                                    }
                                }
                                if( org.apache.commons.lang.StringUtils.isNotEmpty(citycode) ){
                                    if (CollectionUtil.isNotEmpty(locationList)) {
                                        for (ConsumerLocation consumerLocation : locationList) {
                                            consumerLocation.setCitycode(citycode);
                                        }
                                    }
                                    consumer.setCitycode(citycode);
                                }
                                if( org.apache.commons.lang.StringUtils.isNotEmpty(district) ){
                                    if (CollectionUtil.isNotEmpty(locationList)) {
                                        for (ConsumerLocation consumerLocation : locationList) {
                                            consumerLocation.setDistrict(district);
                                        }
                                    }
                                }
                                if( org.apache.commons.lang.StringUtils.isNotEmpty(adCode) ){
                                    if (CollectionUtil.isNotEmpty(locationList)) {
                                        for (ConsumerLocation consumerLocation : locationList) {
                                            consumerLocation.setAdcode(adCode);
                                        }
                                    }
                                    consumer.setDistrictcode(adCode);
                                }
                                if( org.apache.commons.lang.StringUtils.isNotEmpty(towncode) ){
                                    if (CollectionUtil.isNotEmpty(locationList)) {
                                        for (ConsumerLocation consumerLocation : locationList) {
                                            consumerLocation.setTowncode(towncode);
                                        }
                                    }
                                    consumer.setTowncode(towncode);
                                }
                                if( org.apache.commons.lang.StringUtils.isNotEmpty(township) ){
                                    if (CollectionUtil.isNotEmpty(locationList)) {
                                        for (ConsumerLocation consumerLocation : locationList) {
                                            consumerLocation.setTownship(township);
                                        }
                                    }
                                }
                                if (CollectionUtil.isNotEmpty(locationList)) {
                                    for (ConsumerLocation consumerLocation : locationList) {
                                        consumerLocation.setLat(lat);
                                        consumerLocation.setLng(lng);
                                    }
                                    consumerLocationService.saveOrUpdateBatch(locationList);
                                }
                            }
                            if (CollectionUtil.isNotEmpty(dtuList)) {
                                for (Dtu dtu : dtuList) {
                                    dtu.setPositionLat(lat);
                                    dtu.setPositionLon(lng);
                                }
                                equipmentService.saveOrUpdateBatch(dtuList);
                            }
                        }
                    }

                }
                this.saveOrUpdateBatch(consumers);
            }
            consumers.clear();
        }while(total > (pageIndex - 1) * pageSize);
    }

    @Override
    public void updateConsumer(List<Consumer> consumerList) {
        if (!CollectionUtils.isEmpty(consumerList)) {
            this.saveOrUpdateBatch(consumerList);
        }
    }

    @Override
    public String getConsumerRelateSpId(Integer consumerId, String originSpId) {
        String spId = originSpId;
        if (null == consumerId || consumerId <= 0) {
            return spId;
        }
        Consumer consumer = consumerMapper.selectById(consumerId);
        log.info("getConsumerRelateSpId consumer:{}", JSONObject.toJSONString(consumer));
        if (null != consumer && !StringUtils.isEmpty(consumer.getOrgCode())) {
            LambdaQueryWrapper<CompanyEntry> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(CompanyEntry::getCode, consumer.getOrgCode());
            queryWrapper.eq(CompanyEntry::getIsDeleted, false);
            List<CompanyEntry> companyEntryList = companyService.list(queryWrapper);
            if (null != companyEntryList && !companyEntryList.isEmpty()) {
                spId = companyEntryList.get(0).getId();
                log.info("getConsumerRelateSpId spId change:{}", spId);
            }
        }
        return spId;

    }

    @Override
    public Map<String, Integer> getConditionList() {
        String spId = ApplicationUtils.getWorkingSpId();
        List<String> spIds = organizationService.getSpIds(spId);
        Map<String, Integer> map = new HashMap<>();
        //数据权限
        //UserFuncCodePermissionDTO userFuncCodePermission = userPermissionService.getUserDepartPermission(spIds);

        //设备状态：0总数 1报警 2故障 3离线 4正常
        Integer all = this.baseMapper.getConditionList(spIds, null);
        Integer alarm = this.baseMapper.getConditionList(spIds, Arrays.asList(2,3,6));
        Integer breakdown = this.baseMapper.getConditionList(spIds, Arrays.asList(4));
        Integer offline = this.baseMapper.getConditionList(spIds, Arrays.asList(0));
        Integer normal = this.baseMapper.getConditionList(spIds, Arrays.asList(1));
        map.put("总数", all);
        map.put("报警",alarm);
        map.put("故障", breakdown);
        map.put("离线", offline);
        map.put("正常",normal);
        return map;
    }

    private ConsumerRequest mapGeoCoding(ConsumerRequest request){
        double[] location = locationUtil.baiDuUrlGeocoding(request.getCustAddress());
        //维度
        double lat = location[0];
        //经度
        double lng = location[1];
        if (lat>0 && lng>0) {
            request.setAdCode("");
            request.setPositionLat(lat);
            request.setPositionLon(lng);
        }else{
            request.setAdCode("");
            request.setPositionLat(null);
            request.setPositionLon(null);
        }
        return request;
    }
}
